问题
I am running Django 1.2.2 and I get the following error when I try to log in to the Django admin:
Forbidden (403) CSRF verification failed. Request aborted.
Reason given for failure:
No CSRF or session cookie.
** I have made NO customization to the barebones admin and when I inspect the source there is a CSRF token in the form in what I believe is the correct place.
When I look at the actual request that is being sent there is a csrf token being sent but Django still says CSRF verification failed.
Can anyone point me in the right direction? Why is this happening?
回答1:
1) Do you have 'django.middleware.csrf.CsrfViewMiddleware' in your settings.MIDDLEWARE_CLASSES ?
2) Are you sure you've always been on 1.2.2? That only came out last night...
回答2:
I've had the same problem on Django 1.2.1 FINAL. Since I knew that Django on our production site would never be updated from 1.0 (for various reasons), I found a workaround which I implemented into my development version of settings.py, leaving the production settings.py untouched.
Create a middleware.py file in your application directory with the following code:
class disableCSRF:
def process_request(self, request):
setattr(request, '_dont_enforce_csrf_checks', True)
return None
Then in your development version of settings.py, insert this into MIDDLEWARE_CLASSES:
'your_app_name.middleware.disableCSRF',
Perhaps not the safest solution, but our Django site is strictly internal, so there is a minimum risk for any type of malicious actions. This solution is simple and doesn't involve changes to templates/views, and it worked instantly (unlike other I've tried).
Hopefully someone in a similar situation to mine will find this useful.
Credit goes to John McCollum, on whose site I've found this.
回答3:
According to the docs, not only do you need the csrf hidden form field, but also the csrftoken cookie. The error message you provided also suggests a missing cookie.
I would look in your browser's cookies to ensure the csrftoken cookie is present.
来源:https://stackoverflow.com/questions/3678238/why-is-django-admin-login-giving-me-403-csrf-error