2
votes

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!

2

2 Answers

5
votes

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

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.