[Django]-Django โ€“ 403 Forbidden. CSRF token missing or incorrect

7๐Ÿ‘

โœ…

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})
๐Ÿ‘คcold_coder

0๐Ÿ‘

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.

๐Ÿ‘คf43d65

Leave a comment