Django - 403 Forbidden. CSRF token missing or incorrect

痞子三分冷 提交于 2019-12-23 02:39:39

问题


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!


回答1:


Add csrf_exempt to your views.py after importing it like this:

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})



回答2:


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.



来源:https://stackoverflow.com/questions/31618410/django-403-forbidden-csrf-token-missing-or-incorrect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!