30π
Update: This answer is from 2011. CSRF is easy today.
These days you should be using the render
shortcut function return render(request, 'template.html')
which uses RequestContext
automatically so the advice below is outdated by 8 years.
- Use
render
https://docs.djangoproject.com/en/2.2/topics/http/shortcuts/ - Add CSRF middleware https://docs.djangoproject.com/en/2.2/ref/csrf/
- Use the
{% csrf_token %}
template tag - Confirm you see the CSRF token value being generated, AND submitted in your form request
Original Response
My guess is that you have the tag in the template but itβs not rendering anything (or did you mean you confirmed in the actual HTML that a CSRF token is being generated?)
Either use RequestContext
instead of a dictionary
render_to_response("foo.html", RequestContext(request, {}))
Or make sure you have django.core.context_processors.csrf
in your CONTEXT_PROCESSORS
setting.
6π
Just add this to your views
return render_to_response("register.html", {'form': form, }, context_instance = RequestContext(request))
It will work!!
- [Django]-Problems with contenttypes when loading a fixture in Django
- [Django]-Edit/show Primary Key in Django Admin
- [Django]-Import data from excel spreadsheet to django model
4π
Try using render instead of render_to_response:
from django.shortcuts import render
render(request, "foo.html", {})
Django β what is the difference between render(), render_to_response() and direct_to_template()?
As stated in the link above it was introduced in Django 1.3 and automatically uses RequestContext
- [Django]-How to manually assign imagefield in Django
- [Django]-Django authentication without a password
- [Django]-How to validate a field on update in DRF?
1π
for Django version 3.0 add the below annotation
@csrf_protect
def yourfunc(request):
return render(request, '../your.html', None)
And donβt forget add the below tag in your field
<form action="add/" method="post">
{% csrf_token %}
...
</form>
- [Django]-GeoDjango on Windows: "Could not find the GDAL library" / "OSError: [WinError 126] The specified module could not be found"
- [Django]-How to set a Django model field's default value to a function call / callable (e.g., a date relative to the time of model object creation)
- [Django]-Django plural for templates
0π
If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data.
- [Django]-Populating django field with pre_save()?
- [Django]-How to dynamically provide lookup field name in Django query?
- [Django]-Django post_save signals on update
0π
The addition of RequestContext
is the key when using render_to_response
as mentioned by @Yuji βTomitaβ Tomita and @Njogu Mbau. However, what initially threw me off when I was struggling with this problem was that I had to add RequestContext
to both the function in views.py
that initially loads the template and to the function in views.py
that handles the submission from the template.
Also, just for reference, here are some other links that discuss this same problem
- [Django]-How can modify request.data in django REST framework
- [Django]-How to set a Django model field's default value to a function call / callable (e.g., a date relative to the time of model object creation)
- [Django]-Extending Django Admin Templates β altering change list
0π
Also got this error randomly on some pages after I installed django-livereload-server. Uninstalling django-livereload-server did the trick.
- [Django]-Django: Display current locale in a template
- [Django]-PyCharm code inspection complains template file not found, how to fix?
- [Django]-Django template display item value or empty string
0π
I had this issue too, but honestly, I hit refresh on my browser a few minutes later without changing anything and it worked that time. I had this message in my command line as so it might provide a clue as to what was causing the issue:
Not Found: /css/reset/reset.css
[03/Jul/2020 20:52:13] "GET /css/reset/reset.css HTTP/......
- [Django]-Which Stack-Overflow style Markdown (WMD) JavaScript editor should we use?
- [Django]-Django: Example of generic relations using the contenttypes framework?
- [Django]-Migrating existing auth.User data to new Django 1.5 custom user model?
0π
DJANGO/AJAX WORKFLOW FULL METHOD IS HERE π
const url = "{% url 'YOUR_URL_NAME' pk=12345 %}".replace(/12345/, id.toString());
$.ajax({
type: 'POST',
url: url,
data: {'id':id, "csrfmiddlewaretoken": '{{csrf_token}}'},
beforeSend: function() { $('#response').text('Please wait ...'); },
success: function (response) {
console.log(response)
},
error: function (response) {
console.log(response)
}
})
Hope It Will Work !!!
- [Django]-Django catch-all URL without breaking APPEND_SLASH
- [Django]-How to render .rst files in a markdown or html format?
- [Django]-Chained method calls indentation style in Python
-1π
What worked for me was commenting out the below line from my settings.py
'django.middleware.csrf.CsrfViewMiddleware'
- [Django]-Django form β set label
- [Django]-Disable button after submit with jQuery
- [Django]-Django: Difference between using server through manage.py and other servers like gunicorn etc. Which is better?