403 Forbidden. CSRF token missing or incorrect

I try to add ModelForm for my model, but every POST attempt ends with "403 Forbidden. CSRF verification failed. Request aborted. Reason given for failure: CSRF token missing or incorrect". I have no render_to_response() method, so I can't fix this problem by adding RequestContext. Here's my model:

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

Here's my 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})

And here's part of new.html:

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

And another one question: is "text_name" method name ok? Thank you so much!


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

In imports add

from django.shortcuts import redirect

Replace

return HttpResponse('Test')

with

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

Also, add 'django.middleware.csrf.CsrfViewMiddleware' to MIDDLEWARE_CLASSES in settings.py .

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

上一篇: CSRF令牌只是在Django中随机激发

下一篇: 403禁止。 CSRF令牌丢失或不正确