403禁止。 CSRF令牌丢失或不正确

我尝试为我的模型添加ModelForm,但每次POST尝试都以“403 Forbidden结束,CSRF验证失败,请求中止,失败的原因:CSRF令牌丢失或不正确”。 我没有render_to_response()方法,所以我无法通过添加RequestContext来解决这个问题。 这是我的模型:

from django.db import models
from django.forms import ModelForm
.
.
.
class Text(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()

    def __str__(self):
        return self.title

class TextForm(ModelForm):
    class Meta:
        model = Text
        fields = '__all__'

这是我的views.py:

from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from .models import Text, TextForm
.
.
.
def text_new(request):
    if request.method == 'POST':
        form = TextForm(request.POST)
        if form.is_valid():
            return HttpResponse('Test')
    else:
        form = TextForm()

    return render(request, 'projectname/new.html', {'form': form})

这里是new.html的一部分:

<form method="post" action="">
  {% csrf_token %}
  {{ form }}
  <input type="submit" value="Submit" />
</form>

还有一个问题:是“text_name”方法名称好吗? 非常感谢!


在导入之后,将csrf_exempt添加到您的views.py中,如下所示:

from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from .models import Text, TextForm
from django.views.decorators.csrf import csrf_exempt,csrf_protect #Add this
.
.
. 
@csrf_exempt #This skips csrf validation. Use csrf_protect to have validation
def text_new(request):
    if request.method == 'POST':
        form = TextForm(request.POST)
        if form.is_valid():
            return HttpResponse('Test')
    else:
        form = TextForm()

    return render(request, 'projectname/new.html', {'form': form})

在进口中添加

from django.shortcuts import redirect

更换

return HttpResponse('Test')

return redirect('/') # or some other url of your URLconf

另外,在settings.py添加'django.middleware.csrf.CsrfViewMiddleware'MIDDLEWARE_CLASSES

链接地址: http://www.djcxy.com/p/56523.html

上一篇: 403 Forbidden. CSRF token missing or incorrect

下一篇: Django: CSRF token missing or incorrect. / avoid {% csrf