'403 CSRF error on page refresh after login() Django?
So the code is very simple:
views.py
@csrf_protect
def index(request):
global userPersonalInformation
if request.method == "POST":
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
profile = Profile.objects.get(username=username)
return render(request, 'main/profile.html', {"profile":profile})
else:
if CheckUser(username, password):
user = User.objects.create_user(request.POST['username'], userPersonalInformation['email'], request.POST['password'])
user.save()
profile = Profile.objects.create(username=username,school=userPersonalInformation['school'],img=userPersonalInformation['img'], birthyear=userPersonalInformation['birthyear'],city=userPersonalInformation['city'],solved=progress['denominator'])
profile.save()
login(request, user)
return render(request, 'main/profile.html', {"profile": profile })
else:
context = {"form": Userform(request.POST or None), }
return render(request, 'main/login.html', context)
else:
form = Userform()
context = {"form": form, }
return render(request, 'main/login.html', context)
profile.html
{% block title %}Profile | {{ user.first_name }}
And this displays Profile | username correctly on the title bar. i.e. User is logged in.
Settings.py
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
main/urls.py
from django.conf.urls import url
from . import views
app_name = 'main'
urlpatterns = [
url(r'^$', views.index, name='index'),
]
login.html
{% extends "main/base.html" %}
{% block title %}Sign in{% endblock %}
{% block body %}
<div class="container">
<form method="post" action="" class="form-signin">
<h2 class="form-signin-heading">Please sign in</h2>
{% csrf_token %}
{{ form.as_p }}
<button class="btn btn-primary" type="submit">Sign in</button>
</form>
</div>
{% endblock %}
form.py
from django import forms
from django.contrib.auth.models import User
class Userform(forms.Form):
class Meta:
model= User
fields = ('username', 'password')
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput())
Checkuser
CheckUser()
return True
Now the problem is when I click sign in button, I am on the profile page with all the information displayed. But the moment I page refresh, I get this error:
Forbidden (403)
CSRF verification failed. Request aborted.
Please help me. Profile is another table in the database which has the contents of user. The primary key for both tables user and profile is the username. The function CheckUser if user is a valid user of another website which I'm crawling.If he is, we save his details to our database and userPersonalInformation is a global dictionary.
Django Version 1.10
Solution 1:[1]
This is happening because you are render
ing the profile template in the same view where you process the login credentials.
When you refresh the page after you login, the form data you sent to login is resent to the server along with the old csrftoken
, thus causing a CSRF Error
.
To stop this, you should separate your login and profile view.
You can have a view to process the login information and then use django's redirect
function to redirect the user to profile view if the login is successful.
You can use the redirect function like this:
login(request, user)
return redirect('/profile/')
In your urls:
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^profile/$', views.profile, name='profile'),
]
Solution 2:[2]
Try this
from django.views.decorators.csrf import ensure_csrf_cookie
@ensure_csrf_cookie
@csrf_protect
def index(request):
global ....
Solution 3:[3]
this worked for me.
# create a function to redirect profile.html
def user_profile_return_home(request):
return render(request, 'userapp/user_profile.html')
# if user is existed redirect the user_profile_return_home
@ensure_csrf_cookie
@csrf_protect
def user_signin(request):
if request.method == 'POST':
user_username = request.POST.get('user_username')
user_password = request.POST.get('user_password')
user = authenticate(username=user_username, password=user_password)`enter code here`
if user is not None:
login(request, user)
return redirect('profile_return_home')
else:
messages.error(request, 'Bad Credentials!!!')
# redirct happens here
return redirect('user_login_reg')
return render(request, 'userapp/user_sign-in+registration.html')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | itzMEonTV |
Solution 3 | Sirajudheen |