我已经查看了许多关于同样错误的其他Stack问题,但这些解决方案似乎都不适用于我。
我要做的是有一个表格,我可以输入数据并发送电子邮件。
这是我的代码:
#urls.py
from django.conf.urls import patterns, include, url
from webpage import views
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^careeropp/','webpage.views.careeropp'),
url(r'^thanks/','webpage.views.thanks'),
url(r'^admin/', include(admin.site.urls)),
)
#views.py
from django.shortcuts import render_to_response
from webpage.forms import ApplyForm
from django.http import HttpResponseRedirect
from django.core.mail import send_mail
from django.template import RequestContext
from django.core.context_processors import csrf
from django.views.decorators.csrf import csrf_protect
@csrf_protect
def careeropp(request):
if request.method == 'POST':
form = ApplyForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
send_mail(
cd['name'],
cd['email'],
cd.get('email','emailaddress@gmail.com'),
['email@gmail.com'],
)
return HttpResponseRedirect('/thanks/',context_instance=RequestContext(request))
else:
form = ApplyForm()
return render_to_response('webpage/careeropp.html', {'form': form}, context_instance=RequestContext(request))
def thanks(request):
return render_to_response('webpage/thanks.html')
#careeropp.html
<form enctype="text/plain" method="POST" action="">{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<input type="submit" value="Submit">
</form>
我还检查了我的设置,以确保csrf在中间件中。
当我在浏览器中加载careeropp.html时,我可以看到表单完美显示。当我转到页面源时,csrf令牌就在那里。但是,只要我按下提交(无论我是否填写了表单),它就会重定向到403错误:csrf令牌丢失或不正确。
我是网络开发和Django的新手,所以希望我没有犯下一个愚蠢的错误,有人可以提供帮助。