Error CSRF token missing or incorrect while post parameter via AJAX in Django

0 votes

I try to post parameter like

 jQuery.ajax(
        {
            'type': 'POST',
            'url': url,
            'contentType': 'application/json',
            'data': "{content:'xxx'}",
            'dataType': 'json',
            'success': rateReviewResult 
        }
    );

However, Django return Forbidden 403. CSRF verification failed. Request aborted. I am using 'django.middleware.csrf.CsrfViewMiddleware' and couldn't find how I can prevent this problem without compromising security.

Aug 13, 2020 in Python by kartik
• 37,520 points
13,130 views

1 answer to this question.

0 votes

Hello @kartik,

The simplest way to include the {{csrf_token}} value in the data:

jQuery.ajax(
    {
        'type': 'POST',
        'url': url,
        'contentType': 'application/json',
        'data': {
            'content': 'xxx',
            'csrfmiddlewaretoken': '{{ csrf_token }}',
        },
        'dataType': 'json',
        'success': rateReviewResult 
    }
);

Hope it helps!!
Thank you!

answered Aug 13, 2020 by Niroj
• 82,840 points

Related Questions In Python

+2 votes
2 answers

Error while printing hello world in python.

You must be trying this command in ...READ MORE

answered Mar 31, 2018 in Python by GandalfDwhite
• 1,320 points
6,494 views
0 votes
1 answer

How to switch pages using Ajax in Django?

You should use django-pjax which is built exactly for ...READ MORE

answered Oct 9, 2018 in Python by aryya
• 7,460 points
1,596 views
0 votes
1 answer

Error while installing cv2 module in pycharm

Go to tools -> python console -> ...READ MORE

answered Jun 24, 2019 in Python by Quin
11,744 views
0 votes
1 answer

How to temporarily disable a foreign key constraint in MySQL?

Hello @kartik, To turn off foreign key constraint ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,840 points
2,510 views
0 votes
1 answer

How do I use Django templates without the rest of Django?

Hello @kartik, Let's say you have this important ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,840 points
1,586 views
0 votes
1 answer

Error: port is already in use of Django Server

Hii @kartik, Just type sudo fuser -k 8000/tcp. This ...READ MORE

answered May 6, 2020 in Python by Niroj
• 82,840 points
15,660 views
0 votes
1 answer

Error:django-debug-toolbar breaking on admin while getting sql stats

Hello @kartik, You just need to be able ...READ MORE

answered Jun 12, 2020 in Python by Niroj
• 82,840 points
1,301 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP