Question: Django 1.10 Using csrf Token


Django 1.10 Using csrf Token

Answers 4
Added at 2016-12-28 01:12

Novice Django user here. I am trying to use csrf for my form because if I don't I get this message: (and of course protection against forgery)

CSRF verification failed. Request aborted.

Here is my code:

from django.views.decorators.csrf import csrf

def login(request):
    c = {}
    return render_to_response('login.html', c)

So in django 1.9 and older there was something like this:

from django.core.context_processors import csrf

But I get the following error:

'module' object is not callable

Any help? Thanks

EDIT: Full track back:


Request Method: GET
Request URL: http://localhost:8000/accounts/login/

Django Version: 1.10.3
Python Version: 2.7.12
Installed Applications:
Installed Middleware:

File "C:\Python27\lib\site-packages\django\core\handlers\" in inner
  39.             response = get_response(request)

File "C:\Python27\lib\site-packages\django\core\handlers\" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "C:\Python27\lib\site-packages\django\core\handlers\" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\Andy\Documents\ece496-web\capstone\" in login
  9.     c.update(csrf(request))

Exception Type: TypeError at /accounts/login/
Exception Value: 'module' object is not callable
Answers to

Django 1.10 Using csrf Token

nr: #1 dodano: 2016-12-28 01:12

Just make sure to include {% csrf_token %} to your form in your template and it will be ok, e.g:

<form action="." method="post" class="login-form">
    {% csrf_token %}
    <input type="submit" value="Log in" />
nr: #2 dodano: 2016-12-28 01:12

Oops, figured out my mistake. Remove this line:


and it works!

Happy holidays :)

nr: #3 dodano: 2016-12-28 03:12

The view decorator requires_csrf_token can be used to ensure the template tag does work.

from django.views.decorators.csrf import requires_csrf_token
from django.shortcuts import render

def login(request):
    c = {}
    return render_to_response('login.html', c)

Refer to document:

nr: #4 dodano: 2016-12-28 11:12

You should use render() instead of render_to_response(). render() will call your context processors, including the one that adds the csrf token to the context:

from django.shortcuts import render

def login(request):
    return render(request, 'login.html', c)

Then you can simply use {% csrf_token %} inside the form in your template.

It is generally always recommended to use render() over render_to_response():

This function preceded the introduction of render() and works similarly except that it doesn’t make the request available in the response. It’s not recommended and is likely to be deprecated in the future.

Source Show
◀ Wstecz