312👍
If you just need some views not to use CSRF, you can use @csrf_exempt
:
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def my_view(request):
return HttpResponse('Hello world')
You can find more examples and other scenarios in the Django documentation:
62👍
In setting.py
in MIDDLEWARE you can simply remove/comment this line:
'django.middleware.csrf.CsrfViewMiddleware',
- [Django]-Django-tables2: How to use accessor to bring in foreign columns?
- [Django]-Django CSRF check failing with an Ajax POST request
- [Django]-Copy a database column into another in Django
58👍
To disable CSRF for class-based views, the following worked for me.
I’m using Django 1.10 and Python 3.5.2
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
@method_decorator(csrf_exempt, name='dispatch')
class TestView(View):
def post(self, request, *args, **kwargs):
return HttpResponse('Hello world')
- [Django]-Celery missed heartbeat (on_node_lost)
- [Django]-Django Rest Framework remove csrf
- [Django]-Django create userprofile if does not exist
46👍
The problem here is that SessionAuthentication performs its own CSRF validation. That is why you get the CSRF missing error even when the CSRF Middleware is commented.
You could add @csrf_exempt to every view, but if you want to disable CSRF and have session authentication for the whole app, you can add an extra middleware like this –
class DisableCSRFMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
setattr(request, '_dont_enforce_csrf_checks', True)
response = self.get_response(request)
return response
I created this class in myapp/middle.py
Then import this middleware in Middleware in settings.py
MIDDLEWARE = [
'django.middleware.common.CommonMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
#'django.middleware.csrf.CsrfViewMiddleware',
'myapp.middle.DisableCSRFMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
That works with DRF on django 1.11
- [Django]-OneToOneField() vs ForeignKey() in Django
- [Django]-Visual Editor for Django Templates?
- [Django]-How to reset Django admin password?
18👍
For Django 2:
from django.utils.deprecation import MiddlewareMixin
class DisableCSRF(MiddlewareMixin):
def process_request(self, request):
setattr(request, '_dont_enforce_csrf_checks', True)
That middleware must be added to settings.MIDDLEWARE
when appropriate (in your test settings for example).
Note: the setting isn’t not called MIDDLEWARE_CLASSES
anymore.
- [Django]-Copy a database column into another in Django
- [Django]-TypeError: data.forEach is not a function
- [Django]-Django migration fails with "__fake__.DoesNotExist: Permission matching query does not exist."
13👍
The answer might be inappropriate, but I hope it helps you
class DisableCSRFOnDebug(object):
def process_request(self, request):
if settings.DEBUG:
setattr(request, '_dont_enforce_csrf_checks', True)
Having middleware like this helps to debug requests and to check csrf in production servers.
- [Django]-Django storages: Import Error – no module named storages
- [Django]-Iterating over related objects in Django: loop over query set or use one-liner select_related (or prefetch_related)
- [Django]-Filtering using viewsets in django rest framework
9👍
If you want disable it in Global, you can write a custom middleware, like this
from django.utils.deprecation import MiddlewareMixin
class DisableCsrfCheck(MiddlewareMixin):
def process_request(self, req):
attr = '_dont_enforce_csrf_checks'
if not getattr(req, attr, False):
setattr(req, attr, True)
then add this class youappname.middlewarefilename.DisableCsrfCheck
to MIDDLEWARE_CLASSES
lists, before django.middleware.csrf.CsrfViewMiddleware
- [Django]-Django url tag multiple parameters
- [Django]-Django staticfiles not found on Heroku (with whitenoise)
- [Django]-How to filter objects for count annotation in Django?
5👍
Before using this solution, please read this link from documentation
I solved this problem with the following two steps:
-
Add this class to an
utils.py
file:from django.utils.deprecation import MiddlewareMixin from <your-project-name> import settings class DisableCSRF(MiddlewareMixin): def process_request(self, request): if settings.DEBUG: setattr(request, '_dont_enforce_csrf_checks', True)
-
And in the
settings.py
file, add above middleware to theMIDDLEWARE
list:... MIDDLEWARE = [ ... 'django.middleware.csrf.CsrfViewMiddleware', ... '<path-of-utils.py>.utils.DisableCSRF', ] ...
- [Django]-Django.db.migrations.exceptions.InconsistentMigrationHistory
- [Django]-Django rest framework change primary key to use a unqiue field
- [Django]-Django datetime issues (default=datetime.now())
1👍
CSRF can be enforced at the view level, which can’t be disabled globally.
In some cases this is a pain, but um, “it’s for security”. Gotta retain those AAA ratings.
https://docs.djangoproject.com/en/dev/ref/csrf/#contrib-and-reusable-apps
- [Django]-Django 1.3.1 compilemessages. Error: sh: msgfmt: command not found
- [Django]-OneToOneField() vs ForeignKey() in Django
- [Django]-How to access a dictionary element in a Django template?