Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Persistent "CSRF token missing or incorrect.". Jinja and django-registration setup

I receive this message:

CSRF token missing or incorrect.

In most forums, the tell you to get the {% csrf_token %} in the form, and i do have it.

Also i have in my settings.py:

TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.csrf",
"django.contrib.auth.context_processors.auth",
)

I am using jinja, which didn't seem to use CSRF, but then i installed django registration and i got lost, since, it seems to be using some other views, that i don't have access to so to say, they are not written by me, and i can't figure out where they are. "standard auth views" as they call them. So i am unable to add "RequestContext".

Any ideas what's going on and how I can get it going? thanx

like image 402
mgPePe Avatar asked Nov 14 '22 05:11

mgPePe


2 Answers

You might have to rewrite the django-registration view manually. Looks like there's an issue with how Jinja likes to do things and how Django wants to configure template loaders..

To look at the standard auth views, just look under "site-packages" in your python installation.

You could try wrapping the standard auth views like this:

from django.contrib.auth.views import login, logout
from django.views.decorators.csrf import csrf_protect

@csrf_protect
def my_wrapped_login_view(request):
    return login(request)

@csrf_protect
def my_wrapped_logout_view(request):
    return logout(request)

I basically imported Django's standard auth views and called them with my own, which have the csrf_protect decoration. It's worth a shot.

like image 171
Evan Porter Avatar answered Dec 19 '22 02:12

Evan Porter


Have you also got the standard Django Templating system installed? That will be required for most apps that are distributed with templates.

For CSRF, a context processor inserts the variable 'csrf_token' into the response context that it retrieves from the middleware if enabled. Now all you have to do, is make sure that it's apart of your form.

This is straight out of django.core, and is subject to change at any time.

        if csrf_token:
            if csrf_token == 'NOTPROVIDED':
                return mark_safe(u"")
            else:
                return mark_safe(u"<div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='%s' /></div>" % csrf_token)

However, seeing that, all you really need to know is that you have to have an input type named csrfmiddlewaretoken with the value of context.get('csrf_token','') within your form and that's all she wrote.

like image 41
Josh Smeaton Avatar answered Dec 19 '22 01:12

Josh Smeaton