Django 'CSRFCheck' object has no attribute

2019-08-29 21:46发布

问题:

It was all ok till suddenly I got the above error while implementing DjangoObjectPermissions on my APIs.

Before this It was working ok even my production environment it is working fine. I am seeing this error on my local environment only.

according to this answer, the error would go away, but I need to know why?

Please let me know what information should I add to this post.

Following are the related packages installed.

Django==1.10
django-allauth==0.29.0
django-angular==0.8.3
django-debug-toolbar==1.6
django-debug-toolbar-request-history==0.0.3
django-debug-toolbar-template-profiler==1.0.1
django-debug-toolbar-template-timings==0.7
djangorestframework==3.5.3

回答1:

Add try/except statement to enforce_csrf()

Note that this error originates from rest_framework/authentication.py, within class SessionAuthentication, method enforce_csrf(). The enforce_csrf() method iinitiates variable, check = CSRFCheck(), and the next line says "check.process_request(request).

If using an IDE, you'll quickly notice that CSRFCheck() doesn't have this attribute/method thus the error. Many developers will quickly tell you to upgrade to django >= 1.11.6 but you are bound to run into the same error. For that matter, am using django 1.11.6 and rest_framework 3.9.1.

So try this remedy, it worked for me. Use the try/except statement. Go within the rest_framework/authentication.py, below, check = CSRFCheck(), add this...

def enforce_csrf(self, request):
   ...
   try:
       check.process_request(request)
   except:
       pass

What the lines say is this: After declaring the "check" variable, call (try) this method "process_request()" and if it does not work (except), just pass. You achieve two things with this: One, you literally leave the rest_framework source code compatible (given that upgrading to further versions of django "might" solve this), and two, you get working code (nice!!, especially if working Agile)