The error I've been getting is this :
Reason given for failure: CSRF token missing or incorrect.
In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure :
- Your browser is accepting cookies.
- The view function passes a request to the template's render method.
- 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.
<html>
<head>
<meta charset="UTF-8">
<title>Log In</title>
</head>
<body>
<div class="container" style="max-width:400px">
<form method="post" class="form-signin">{% csrf_token %}
<h2 class="form-signin-heading">Please Log in</h2>
<input type="text" name="username" class="form-control" placeholder="username" autofocus>
<input type="password" name="password" class="form-control" placeholder="Password">
<button class="btn btn-lg btn-primary btn-block" type="submit">Log in</button>
</form>
<p>{{error}}</p>
</div> <!-- /container -->
</body>
</html>
I tried to put in context
but that didn't make the error go away either :
# views.py
def login(request):
if request.user.username and request.user.profile.is_chat_user:
return HttpResponseRedirect(reverse('index'))
context = {'error':''}
if request.method == 'POST':
username = request.POST.get('username','') #retunr '' if no username
password = request.POST.get('password','')
user = auth.authenticate(username=username,password=password)
if user is not None:
auth.login(request,user)
cu = request.user.profile
cu.is_chat_user = True
cu.last_accessed = utcnow()
cu.save()
return HttpResponseRedirect(reverse('index'))
else:
#context['error'] = ' wrong credentials try again'
return render('index.html')
#return render(request,'djangoChat/login.html',context)
#context.update(csrf(request))
return render('index.html')
#return render(request,'djangoChat/login.html',context)
The views.py
file has this : from django.views.decorators.csrf import csrf_exempt
I saw a few similar cases but none of them explained the cause and how to avoid this error.