Avoid csrf error in django 1.4.3

I use django to create a login and logout base page. so below is my code

settings.py

TEMPLATE_CONTEXT_PROCESSORS = ( ........... ........... "django.contrib.messages.context_processors.messages", "django.core.context_processors.request", "django.core.context_processors.csrf", ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) INSTALLED_APPS = ( 'django.contrib.auth', ....... ....... ) 

urls.py

 from django.conf.urls.defaults import * from django.conf import settings urlpatterns = patterns('', url(r'^$', 'learn_django.views.home_page'), url(r'^login/$', 'learn_django.views.login'), url(r'^logged_in$', 'learn_django.views.logged_in'), url(r'^logout/$', 'learn_django.views.logout'), ) if settings.DEBUG: urlpatterns = patterns('', url(r'^media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT, 'show_indexes': True}), ) + urlpatterns 

views.py

 from django.shortcuts import render_to_response from django.template import RequestContext def home_page(request): return render_to_response("home_page.html") def login(request): return render_to_response("login.html") def logged_in(request): return render_to_response("logged_in.html",context_instance=RequestContext(request)) 

base.html

 {% load staticfiles %} <html xmlns="http://www.w3.org/1999/xhtml"> <head> <link rel="stylesheet" href="{% static 'css/home_remaining.css' %}" type="text/css"> <title>{% block title %}{% endblock %}</title> </head> <body> <header> <div class='header_div'> <div class="logout"><p id='logout'><a href="/logout" >Logout</a></p><div> <div class="login"><p id='login'> <a href="/login" >Login</a></p><div> </div> </header> <div class="body_content"> {% block body %}{% endblock %} </div> </body> </html> 

login.html

 {% extends 'base.html' %} {% block title %}Login Page{% endblock %} {% block body %} <div id='container'> <form action="/logged_in" method="POST"> {% csrf_token %} <label for="name">Username:</label><input type="name"> <label for="username">Password:</label><input type="password"> <div id="lower"> <input type="submit" value="Login"> </div> </form> </div> {% endblock %} 

So above is my completion code that displays the login form when we click on the Login link provided in base.html .

After the login displayed and entered a few username and password and pressed the Login button, a page with the message csrf error

Too much googled and added {% csrf_token %} inside the form tags, and also added django.core.context_processors.csrf in the template context in settings.py

So below is the error message.

 Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: CSRF cookie not set. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. The view function uses RequestContext for the template, instead of Context. In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL. If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data. You're seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed. You can customize this page using the CSRF_FAILURE_VIEW setting. 

So, when I removed django.core.context_processors.csrf from the template context process, it works fine. But I also want to use csrf protection.

Finally, and in fact, what is wrong in the above presentation code and why does the csrf error page appear and how to avoid the above error page?

Do I need to add code to my views.py functions?

Can anyone add a basic login and logout code to my functions above to make it more useful to understand the code practically ...

Edited

For the above problem, I imported the csrf_exempt function as shown below

from django.views.decorators.csrf import csrf_exempt

and gave it as a decorator before the logged_in , and it didn’t work showing the error page when I pressed the login button

But still wondering why the methods below, such as sending Requestcontext from templates, do not work

+4
source share
1 answer

You need to pass the RequestContext to your render_to_response function.

 def home_page(request): return render_to_response("home_page.html", context_instance=RequestContext(request)) 

Either that, or use the new rendering function, which handles the RequestContext for you.

 def home_page(request): return render(request, "home_page.html") 

RequestContext adds various useful things to the context dictionary, which is passed to the template. This includes the csrf token. See RequestContext docs for more information.

In your case, your login view displays the login.html template, but does not pass the csrf token. When the login.html template login.html sent back to the server (before /logged_in ), the logged_in checks this csrf token. This is not the case (because you never turned it on). therefore, he assumes that he received a fake cross-site request.

Read the csrf docs for a better understanding of the process.

+5
source

All Articles