53👍
Because you did not post the csrfmiddlewaretoken, so Django forbid you.
this document can help you.
28👍
For the lazy guys:
First download cookie: http://plugins.jquery.com/cookie/
Add it to your html:
<script src="{% static 'designer/js/jquery.cookie.js' %}"></script>
Now you can create a working POST request:
var csrftoken = $.cookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$.ajax(save_url, {
type : 'POST',
contentType : 'application/json',
data : JSON.stringify(canvas),
success: function () {
alert("Saved!");
}
})
- [Django]-Django: Model Form "object has no attribute 'cleaned_data'"
- [Django]-Django can' t load Module 'debug_toolbar': No module named 'debug_toolbar'
- [Django]-Disable link to edit object in django's admin (display list only)?
12👍
The fastest solution if you are not embedding js into your template is:
Put <script type="text/javascript"> window.CSRF_TOKEN = "{{ csrf_token }}"; </script>
before your reference to script.js file in your template, then add csrfmiddlewaretoken
into your data
dictionary:
$.ajax({
type: 'POST',
url: somepathname + "do_it/",
data: {csrfmiddlewaretoken: window.CSRF_TOKEN},
success: function() {
console.log("Success!");
}
})
If you do embed your js into the template, it’s as simple as: data: {csrfmiddlewaretoken: '{{ csrf_token }}'}
- [Django]-What does error mean? : "Forbidden (Referer checking failed – no Referer.):"
- [Django]-Django TypeError: 'RelatedManager' object is not iterable
- [Django]-Celery: When should you choose Redis as a message broker over RabbitMQ?
7👍
I find all previous answers on-spot but let’s put things in context.
The 403 forbidden response comes from the CSRF middleware (see Cross Site Request Forgery protection):
By default, a ‘403 Forbidden’ response is sent to the user if an incoming request fails the checks performed by CsrfViewMiddleware.
Many options are available. I would recommend to follow the answer of @fivef in order to make jQuery add the X-CSRFToken
header before every AJAX request with $.ajaxSetup
.
This answer requires the cookie jQuery plugin. If this is not desirable, another possibility is to add:
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
BUT: if the setting CSRF_COOKIE_HTTPONLY
is set to True, which often happens as the Security middleware recommends so, then the cookie is not there, even if @ensure_csrf_cookie()
is used. In this case {% csrf_token %}
must be provided in every form, which produces an output such as <input name="csrfmiddlewaretoken" value="cr6O9...FUXf6" type="hidden">
. So the csrfToken
variable would simply be obtained with:
var csrftoken = $('input[name="csrfmiddlewaretoken"]').val();
Again $.ajaxSetup
would be required of course.
Other options which are available but not recommended are to disable the middleware or the csrf protection for the specific form with @csrf_exempt()
.
- [Django]-Using django-rest-interface
- [Django]-Using Pylint with Django
- [Django]-Django models | get specific columns
6👍
data: {"csrfmiddlewaretoken" : "{{csrf_token}}"}
You see “403 (FORBIDDEN)”, because you don`t send “csrfmiddlewaretoken” parameter.
In template each form has this: {% csrf_token %}.
You should add “csrfmiddlewaretoken” to your ajax data dictionary. My example is sending “product_code” and “csrfmiddlewaretoken” to app “basket” view “remove”:
$(function(){
$('.card-body').on('click',function(){
$.ajax({
type: "post",
url: "{% url 'basket:remove'%}",
data: {"product_code": "07316", "csrfmiddlewaretoken" : "{{csrf_token}}" }
});
})
});
- [Django]-Django model manager objects.create where is the documentation?
- [Django]-Django F expressions joined field
- [Django]-Do CSRF attacks apply to API's?
2👍
To set the cookie, use the ensure_csrf_cookie
decorator in your view:
from django.views.decorators.csrf import ensure_csrf_cookie
@ensure_csrf_cookie
def hello(request):
code_here()
- [Django]-Django-rest-framework how to make model serializer fields required
- [Django]-In Django, how does one filter a QuerySet with dynamic field lookups?
- [Django]-What is the best way to upload files in a modern browser
2👍
Make sure you aren’t caching the page/view that your form is showing up on. It could be caching your CSRF_TOKEN. Happened to me!
- [Django]-Django ModelForm to have a hidden input
- [Django]-Django-taggit – how do I display the tags related to each record
- [Django]-Checking for empty queryset in Django
2👍
Another approach is to add X-CSRFTOKEN header with the “{{ csrf_token }}” value like in the following example:
$.ajax({
url: "{% url 'register_lowresistancetyres' %}",
type: "POST",
headers: {//<==
"X-CSRFTOKEN": "{{ csrf_token }}"//<==
},
data: $(example_form).serialize(),
success: function(data) {
//Success code
},
error: function () {
//Error code
}
});
- [Django]-Why use Django on Google App Engine?
- [Django]-Cannot import name _uuid_generate_random in heroku django
- [Django]-How to configure where to redirect after a log out in Django?
0👍
Try including this decorator on your dispatch code
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
@method_decorator(csrf_exempt, name='dispatch')
def dispatch(self, request, *args, **kwargs):
return super(LessonUploadWorkView,self).dispatch(request,*args,**kwargs)
- [Django]-Add additional options to Django form select widget
- [Django]-Django composite unique on multiple model fields
- [Django]-Django orm get latest for each group
0👍
With SSL/https and with CSRF_COOKIE_HTTPONLY = False, I still don’t have csrftoken in the cookie, either using the getCookie(name) function proposed in django Doc or the jquery.cookie.js proposed by fivef.
Wtower summary is perfect and I thought it would work after removing CSRF_COOKIE_HTTPONLY from settings.py but it does’nt in https!
Why csrftoken is not visible in document.cookie???
Instead of getting
“django_language=fr; csrftoken=rDrGI5cp98MnooPIsygWIF76vuYTkDIt”
I get only
“django_language=fr”
WHY? Like SSL/https removes X-CSRFToken from headers I thought it was due to the proxy header params of Nginx but apparently not… Any idea?
Unlike django doc Notes, it seems impossible to work with csrf_token in cookies with https. The only way to pass csrftoken is through the DOM by using {% csrf_token %} in html and get it in jQuery by using
var csrftoken = $('input[name="csrfmiddlewaretoken"]').val();
It is then possible to pass it to ajax either by header (xhr.setRequestHeader), either by params.
- [Django]-Django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. (django 2.0.1)(Python 3.6)
- [Django]-Django template comparing string
- [Django]-AssertionError: database connection isn't set to UTC
0👍
this works for me
template.html
$.ajax({
url: "{% url 'XXXXXX' %}",
type: 'POST',
data: {modifica: jsonText, "csrfmiddlewaretoken" : "{{csrf_token}}"},
traditional: true,
dataType: 'html',
success: function(result){
window.location.href = "{% url 'XXX' %}";
}
});
view.py
def aggiornaAttivitaAssegnate(request):
if request.is_ajax():
richiesta = json.loads(request.POST.get('modifica'))
- [Django]-Stack trace from manage.py runserver not appearing
- [Django]-How to make Django QuerySet bulk delete() more efficient
- [Django]-Django rest framework, use different serializers in the same ModelViewSet
- [Django]-Multiple images per Model
- [Django]-How do I use allow_tags in django 2.0 admin?
- [Django]-How to use django-debug-toolbar on AJAX calls?