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

时间:2015-07-24 19:31:47

标签: python django django-forms csrf django-csrf

我尝试为我的模型添加ModelForm,但每次POST尝试都以“403 Forbidden结束.SOAPF验证失败。请求中止。失败原因: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”方法名称好吗?非常感谢你!

2 个答案:

答案 0 :(得分:3)

在导入后将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})

答案 1 :(得分:0)

在导入中添加

from django.shortcuts import redirect

替换

return HttpResponse('Test')

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

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