Django csrf令牌丢失或错误403错误

时间:2017-04-14 11:05:24

标签: python django csrf

当我提交表单时,我收到以下错误:

  

CSRF验证失败

     

失败原因:

CSRF token missing or incorrect.

我的views.py是:

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')

我的setting.py文件:

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',
]

我的forms.py文件是:

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

我的contact.html是:

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

urls.py是:

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)
]

3 个答案:

答案 0 :(得分:2)

使用render功能呈现模板,而不是render_to_response

create different db files using
      >sqlite3 test1.db
sqlite> create table test1 (name text);
sqlite> insert into test1 values('sourav');
sqlite>.exit
      >sqlite3 test2.db
sqlite> create table test2 (eid integer);
sqlite> insert into test2 values (6);
sqlite>.exit
      >sqlite
SQLite version 3.8.5 2014-06-04 14:06:34
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
sqlite> .open test1.db
sqlite> select * from test1;
sourav
sqlite> .open test2.db
sqlite> select * from test1;
Error: no such table: test1
sqlite> select * from test2;
6
sqlite> .exit
      >

Thank YOU.

答案 1 :(得分:0)

使用@csrf_protect装饰器。 您可以获得有关csrf here

的详细信息

答案 2 :(得分:0)

csrf Forbidden (CSRF token missing or incorrect.)提交请求时:

在表单中,包括{% csrf_token %},它会生成带有csrf令牌值的输入标签,并在请求中将标头包括X-CSRFTOKEN

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

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