Django - 403 禁止访问。 CSRF 令牌丢失或不正确

Django - 403 Forbidden. CSRF token missing or incorrect

我尝试为我的模型添加 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