Django is throwing "CSRF token or missing" Error (due to empty csrfmiddlewaretoken)
I recently got stuck on a rather strange problem. I have a form in my template:
<form class="form" id="loginForm" role="form" action="/user/login/"
method="POST">
{% csrf_token %}
<div class="form-group">
<input type="email" class="form-control" id="email" name="email"
placeholder="Enter email" value="">
</div>
<div class="form-group">
<input type="password" class="form-control" id="password"
name="password" placeholder="Password" value="">
</div>
<div class="cl-effect-7">
<button type="submit" class="btn btn-primary">SIGN IN</button>
</div>
</form>
I was getting . Digging further in depth, I found that although the csrftoken cookie is set correctly in the browser, the POST request has an empty csrfmiddlewaretoken and hence it throws an error with the reason
given.Also here is my view (although I doubt there is anything wrong with it So) CSRF token missing or incorrect
def user_login(request):
context = RequestContext(request)
if request.method == 'POST':
email = request.POST['email']
password = request.POST['password']
user = authenticate(username=email, password=password)
if user:
if user.is_active:
login(request, user)
return HttpResponseRedirect('/user/')
else:
return HttpResponse("Your account is disabled.")
else:
return HttpResponse("Invalid login details supplied.")
else:
return render_to_response('user/login.html', {},context_instance = context)
Here's another view that redirects to login.html:
def index(request):
context_dict = {}
template = "user/login.html" #default template to render
user = None
user_profile = None
user = request.user.id
if user != None:
user_profile,created = UserProfile.objects.get_or_create(user=user)
#Check whether the user is new,if yes then he needs to select btw Mentor-Mentee
if user_profile and user_profile.is_new:
context_dict['selected'] = None
template = "user/select.html" #User has to select either Mentor/Mentee,so redirect to select.html
return render_to_response(template,context_dict,context_instance = RequestContext(request))
I have now used a little JavaScript to get around this by manually setting the csrfmiddlewaretoken value from the cookie, but this is a little strange behavior from Django.
PS: I used Django 1.7 and tested this on all browsers.
source to share
Try adding this to your form:
<div style="display:none">
<input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}">
</div>
Source: https://docs.djangoproject.com/en/dev/ref/csrf/#other-template-engines
source to share