Home > OS >  Avoid csrf token in django post method
Avoid csrf token in django post method

Time:12-03

I am making part of the web app where (unlogged users, all visitors) can fill the form and I have to save that data (name, phone number, question) in database.. I am making REST using Django, but for frontend I will use React or Django, and I am making POST method in Django framework that reads JSON data from POST https request, and then I save that data to database.. But I get error CSRF verification failed. Request aborted. because I don not use CSRF token, because it is not required for this (I do not have logged users). But I do not want to disable CSRF, because for admin page I would use this to authenticate users? So anyone knows how to avoid using CSRF token for this method? Thanks in advance..

def saveDataToDatabase(request):
    if request.method == 'POST':
        json_data = json.loads(request.body) 
        try:
            data = json_data['data']
        except KeyError:
            HttpResponseServerError("Malformed data!")

This is the part of method..

CodePudding user response:

It's possible to disable csrf protection on a view with @csrf_exempt decorator.

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def saveDataToDatabase(request):
    # Your code here

More Infos on the Django doc

CodePudding user response:

have you though about using Views to handle the requests? You may use it so you don´t have to do the second advice I´m giving you.

If the first advice wasn´t good enough, you may disable the csrf token in settings file from Django. You need to remove (or comment) the django.middleware.csrf.CsrfViewMiddleware in the Middleware list available.

Any other question just ask ;)

  • Related