在Django表单中,CSRF令牌丢失或不正确

我是Django表格的新手 . 我试图从文本字段中获取一个值并将其存储在数据库中 . 我收到错误报告说:

*禁止(403)CSRF验证失败 . 请求中止 . 失败原因:CSRF令牌丢失或不正确 .

对于POST表单,您需要确保:

您的浏览器正在接受cookies .

视图函数使用RequestContext作为模板,而不是Context .

在模板中,每个POST表单中都有一个{%csrf_token%}模板标记,用于定位内部URL .

如果您不使用CsrfViewMiddleware,则必须在使用csrf_token模板标记的任何视图以及接受POST数据的视图上使用csrf_protect . *

Where am I going wrong?

我的views.py代码是:

from django.shortcuts import render
from feedback.models import Test
from mysite.forms import TestForm
from django.http import HttpResponse
from django.template import Context, loader

def test_view(request):
    form = TestForm
    t = loader.get_template('form.html')
    c = RequestContext(request,{'n':''})
    if request.method=='POST':
        form = TestForm(request.POST)
        if form.is_valid():
            in_name = request.POST.get("firstname")
            fd = Test(name = in_name)
            fd.save()
    return HttpResponse(t.render(c))

我的models.py代码是:

from django.db import models
from django.forms import ModelForm

class Test(models.Model):
      name = models.CharField(max_length=255)

class TestForm(ModelForm):
      class Meta:
           model = Test
           fields = ['name']

我的forms.py代码是:

from django import forms

class TestForm(forms.Form):
      name = forms.CharField()

我的HTML模板是:

<!DOCTYPE html>
<html>
<head>
     <title>test form</title>
</head>

<body>

<form method = "POST">
{% csrf_token %}
First name:<br>
<input type="text" name="firstname" value = {{ n }}>
<br><br><br>
<input type="submit" value="Submit">
</form>
</body>

</html>

回答(1)

2 years ago

你以错误的,非常PHP的方式做到这一点 .

将表单定义从 models.py 移动到 forms.py ,所以 feedback/forms.py 应该是:

from django.forms import ModelForm

class TestForm(forms.ModelForm):
      class Meta:
           model = Test
           fields = ['name']

feedback/views.py 应简化为:

from django.shortcuts import render, redirect

from feedback.forms import TestForm

def test_view(request):
    if request.method == 'POST':
        form = TestForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('.')
    else:
        form = TestForm()
    return render(request, 'form.html', {'form': form})

和模板:

<!DOCTYPE html>
<html>
<head>
     <title>test form</title>
</head>

<body>

    <form method="POST">
        {% csrf_token %}
        {{ form.as_p }}
        <input type="submit" value="Submit">
    </form>

</body>

</html>