python – CSRF error in Django; How can I add CSRF to my login view? – Education Career Blog

I have a simple form I want users to be able to log into; here is the template code with the CSRF tag in it:

<head><title>My Site</title></head>

    <form action="" method="post">{% csrf_token %}
        <label for="username">User name:</label>
        <input type="text" name="username" value="" id="username">
        <label for="password">Password:</label>
        <input type="password" name="password" value="" id="password">

        <input type="submit" value="login" />
        <input type="hidden" name="next" value="{{ next|escape }}" />

Now here is my page. The question is where do I put in the CSRF supporting part (right now I get a CFRS token error) in my view and how do i do it?

from django.contrib import auth

def login_view(request):
    username = request.POST.get('username', '')
    password = request.POST.get('password', '')
    user = auth.authenticate(username=username, password=password)
    if user is not None and user.is_active:
        # Correct password, and the user is marked "active"
        auth.login(request, user)
        # Redirect to a success page
        return HttpResponseRedirect("/account/loggedin/")
        # Show an error page
        return HttpResponseRedirect("account/invalid/")

def logout_view(request):


You have to add the RequestContext to the view that renders the page with the {% csrf_token %} line in it. Here is the example from the tutorial:

# The {% csrf_token %} tag requires information from the request object, which is 
# not normally accessible from within the template context. To fix this, 
# a small adjustment needs to be made to the detail view, so that it looks 
# like the following:
from django.template import RequestContext
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p},

The context_instance=RequestContext(request) part is the important part. This makes the RequestContext available to the form template when it is rendered.

Leave a Comment