Tango
Tango

Reputation: 123

Django csrf token missing or incorrect error 403

When i submit the form i get following error:

CSRF verification failed

Reason given for failure:

CSRF token missing or incorrect.

my views.py is:

def name(request):
   if request.method == 'POST':
        form=NameForm(request.POST)
        if form.is_valid():
            name=form.cleandata['your_name']
            return HttpResponseRedirect('/thanks/',RequestContext(request))

    else:
        form=NameForm()
    return render_to_response('contact.html')

my setting.py file:

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

my forms.py file is:

class NameForm(forms.Form):
    your_name=forms.CharField(initial='your name',max_length=100)

my contact.html is:

<form action="/your-name/" method="POST">
{% csrf_token %}
{{form}}
<input type="submit" value="Submit" />
</form>

urls.py is:

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^search/$', search),url(r'^contact/$',contact),
url(r'^name/$',name),url(r'^your-name',name),url(r'^thanks/$',thank)
]

Upvotes: 3

Views: 8700

Answers (3)

robert wallace
robert wallace

Reputation: 429

csrf Forbidden (CSRF token missing or incorrect.) when submitting a request:

In a form, include {% csrf_token %}, which generates an input tag with the csrf token value, and in the request, have the headers include X-CSRFTOKEN

headers: {
  content_type: 'application/json',
  'X-CSRFToken': "{{ csrf_token }}"
},

https://docs.djangoproject.com/en/3.1/ref/csrf/

Upvotes: 0

nik_m
nik_m

Reputation: 12106

Use the render function to render the template, instead of the render_to_response.

from django.shortcuts import render

def name(request):
  if request.method == 'POST':
    form = NameForm(request.POST)
    if form.is_valid():
        name = form.cleaned_data['your_name']
        return HttpResponseRedirect('/thanks/', RequestContext(request))
    else:
        form = NameForm()
    return render(request, 'contact.html')

Upvotes: 2

Tarikul Islam Rasel
Tarikul Islam Rasel

Reputation: 151

Use @csrf_protect decorator. You can get details about csrf here

Upvotes: 0

Related Questions