Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid csrf token in django post method

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..

like image 582
ProgNow Avatar asked Jul 28 '26 08:07

ProgNow


1 Answers

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

like image 135
Rvector Avatar answered Jul 31 '26 00:07

Rvector