James Franco James Franco - 4 months ago 31
Python Question

Can you construct csrf from request object - csrf constructor exception?

I am following an example of user registration and my code looks like this

from django.views.decorators import csrf
def register_user(request):
args.update(csrf(request)) #---->Crashes here
args["form"] = UserCreationForm()
return render_to_response("register.html",args)

I get an exception at the statement


stating that the

module object is not callable.

Any suggestions on what I might be doing wrong ?


There are two way to CSRF protect your django websites :

1 - Using the middleware, the simplest way :

The django.middleware.csrf.CsrfViewMiddleware automatically adds a CSRF token to the context.

This middleware is enabled by default in your settings.py file and you can directly use this token in your template.

With this solution you have nothing to do but using the {% csrf_token %} tag in your template as bellow.

2 - Using the csrf_protect decorator :

If you deactivate the middleware (which is not recommended), you can still use the csrf_protect decorator (It seems it's the solution you're trying, but not with its correct import as Danielle pointed out).

But your problem seems to be that you don't use it as you should.

It's a decorator, i-e a function that returns a modified version of a function passed as parameter. Here you're passing it a request object.

With Python, you canuse a decorator this way :

def function([...]):

So your view should look like :

def your_view(request, *args, **kwargs):
    # Your view code

Using the {% csrf_token %} tag :

After using one of these solutions, you can directly use the {% csrf_token %} tag in your template since the csrf token should be in your context at template rendering (thanks to either the middleware or the csrf_protect decorator) :

  {% csrf_token %}
  {{ form.as_p }}
  <input type="submit" value="Submit" />

Here is more about CSRF protections with Django :


and here is more about decorators with Python :