问题
I'm writing an enrollment website for my school, and using Django for the framework. For the registration, I require a username, password, and registration token. Those have yet to be validated, all I'm attempting to do right now is go from the registration input page (which uses a POST request) to a "You have successfully registered" page. Somewhere along the line, the csrf token is apparently refusing to be validated.
My view:
def register(request):
return render(request, 'enroller/successfulEnroll.html')
My page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="{% url 'register' %}" method="post"> {% csrf_token %}
<div class="container">
<label><b>New Username</b></label>
<input type="text" placeholder="Username" name="uname" required>
<br>
<label><b>Password</b></label>
<input type="password" placeholder="Password" name="psw" required>
<br>
<label><b>Registration Password</b></label>
<input type="text" placeholder="Registration Key" name="reg" required>
<br>
<input type="submit" value="Register" />
</div>
</form>
</body>
</html>
When I attempt to go from the registration page to the success page, it gives me an error 403 (CSRF Verification failed. Request aborted). However, when I attempt to go to the url mysite.com/register/, it returns the page I requested with no error.
Is there any way to fix this? I've been looking at RequestContext, but I'm not entirely sure where it would be used.
回答1:
Got it to work. Daniel was right - it was a problem with the configuration of my middleware. I added two lines before my middleware array in settings.py, and all of the sudden it worked.
SESSION_COOKIE_SECURE = True
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
I can't say I'm entirely sure why it worked, or what the issue was exactly, but it works now. Thanks Daniel!
回答2:
maybe you can use this method. And djang version is 1.11.1
from django.shortcuts import render
from django.template.context_processors import csrf
form = LoginForm()
c = {'form': form}
c.update(csrf(request))
return render(request, 'a_template.html', c)
I found this method at http://djangobook.com/security-in-django/
For me, work fine, but not the best, because more than a line.
来源:https://stackoverflow.com/questions/40616115/django-403-csrf-verification-failed