Wednesday, February 1, 2012

Re: Using Context Processor as form with HttpResponseRedirect

On Wednesday, 1 February 2012 01:34:03 UTC, richard wrote:
Hi i have seen alot of people saying to use a context processor to
include forms in multiple page. I have written a context processor
login form that just returns the django Authentication form and
everything works great including the form.errors etc except that I
cant seem to redirect from the context processor after is_valid is
called. Are context processors not supposed ot be used in this way? My
thoughts inititally were that if it seems to support a request and can
do the validation why not? Basically stuck on using
HttpResponseRedirect in a context processor. I have managed to get
this working by passing a variable called redirect in the dictionary
returned to my template and then saying if the redirect tag is
available use the browsers meta tag to redirect me but i dont think
this is the way it should work. code below please advise thanks.

context_processors.py

from django.contrib.auth.forms import AuthenticationForm
from django.http import HttpResponseRedirect


def login_form(request):
    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            #return HttpResponseRedirect('/home') ONLY THING THATS NOT
WORKING
            return {'login_form': form, 'redirect': '/home'}
    else:
        form = AuthenticationForm(request)
    return {'login_form': form}

template.html
{{ form.non_field_errors}} # works fine after post with errors showing
{{ form.username}}
{{ form.password}}
{% if redirect %}
   <meta http-equiv="REFRESH" content="0;url={{ redirect }}">
 {% endif %}

No, of course this is not what context processors are for. They are for, er, processing the context. The only thing they can do is add items to the template context before it is rendered. They have no control at all over the response - the template that is being rendered may not even be part of the response (think of an email being created from a template within a view, but the response is rendered from a separate 'confirmation' template).

Rather than putting the form in a context processor, I would use a template tag that only renders the original form. The form itself should post to a specific view, so that the POST is processed there instead of in the context processor.
--
DR.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/RK_TEQKuiJgJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment