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)
]
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With