'CSRF verification failed: is token not persisting between GET and POST? Django
I checked a lot of the older CSRF questions, but they seem to be from 5+ years ago and a lot of the solutions aren't applicable due to now being handled with render() or other built-in methods. So, here's my question:
I'm rendering a form template from a class-based view. It loads fine when I hit the initial GET request, but when I try to submit, it throws a 403: CSRF verification failed error.
I'm not sure why this is happening - I feel like I'm doing everything right. Could it have something to do with saved cookies that override the CSRF token getting changed every time render is called? Here's my code:
class Intake(View):
form_class = IntakeFormSimple
template_name = "intake.html"
def get(self, req: HttpRequest):
form = self.form_class(None)
return render(req, self.template_name, {"form": form})
def post(self, req: HttpRequest):
form = self.form_class(req.POST)
if form.is_valid():
# PLACEHOLDER: I DO SOME STUFF WITH THE SUBMITTED DATA HERE
return HttpResponse("submitted form!")
return render(req, self.template_name, {"form": form})
and the form template (boilerplate removed for clarity):
<body>
<section class="section">
<div class="container">
<form action="" method="post" novalidate>
{% csrf_token %} {{ form.non_field_errors }} {% for field in form %}
<div class="field">
<label class="label" for="{{field.id_for_label}}"
>{{field.label}}</label
>
<div class="control">{{field}}</div>
{% if field.help_text %}
<p class="help">{{field.help_text}}</p>
{% endif %}
<ul class="errorlist">
{% for error in field.errors %}
<li class="is-danger help">{{error}}</li>
{% endfor %}
</ul>
</div>
{% endfor %}
<input type="submit" />
</form>
</div>
</section>
</body>
Solution 1:[1]
You can use this:
#in views.py
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def myView(request):
#your code
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | itsmehemant7 |
