CSRF token missing (403)

Hello @all,

there are many questions regarding this topic and it feels like I have read all. But I still can’t solve this problem.

I can load my form and fill in the fields, but when I send the form I get the error that the csrf token is missing.

Template tag {% csrf_token %} is in the form
‘django.middleware.common.CommonMiddleware’, is used
Cookies are accepted
I can see the csrf token in the form when the site is loaded
Tried different browsers (also privat browsing)
Django version 5.0.7

template

{% block content %}

<div class="row mb-4">
    <div class="col">
        <h3>Registrierung</h3>
        
    </div>
</div>
<div class="row mb-4">
    <div class="col">
        <img src="{% static 'app1/logo.png' %}"><img src="{% static 'logo.png' %}"><a href="/admin">Zum Admin-Login</a>
    </div>
</div>
<div class="row mb-4">
    <div class="col">
        <form  method="post" action="" enctype="text/plain">
            {% csrf_token %}
            {{ form.as_p }}
            <button type="submit"  class="btn btn-success btn-sm">Speichern</button>
        </form>
    </div>
</div>
{% endblock content %}

forms.py

from django import forms
from .models import  Person


class PersonForm(forms.ModelForm):
   
   class Meta:
      model = Person
      fields = '__all__'

models.py

from django.db import models

class Person(models.Model):
    vorname = models.CharField(max_length=50)
    nachname = models.CharField(max_length=50)
    email = models.EmailField()
    phone = models.CharField(max_length=50)

    def __str__(self):
        return self.vorname +' '+ self.nachname

views.py

from django.http import HttpResponseRedirect
from django.shortcuts import render, HttpResponse
from .forms import PersonForm
from django.shortcuts import render, redirect


# Create your views here.
def home(request):
    if request.method == 'POST':
        
        form = PersonForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/success')
    
    else:
        
        form = PersonForm()
        return render(request, 'app1/index.html', {'form': form})
        
    

def success(request):
    return HttpResponse('Hat geklappt')

urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home'),
    path('success', views.success, name='success'),
]

What am I missing? What more can I do to check what’s wrong?

Thanks.

Suhel

Please post the full error message with the traceback (if any) that you are receiving on the server from these requests.

grafik

Forbidden (CSRF token missing.): /
[30/Jul/2024 14:24:48] “POST / HTTP/1.1” 403 2517

local development server 127.0.0.1:8000, Windows + VisualStudio Code

Please post the message and any traceback from the server console where you’re running runserver, not the browser page being returned.

Also, you can use the network tab in your browser’s developer tools to look at the post request being issued. Please verify that you are seeing both the cookie and the csrf_token being returned in the post.

Side note: I’d suggest removing the enctype attribute from your form. That’s not the default enctype for posted data, and it might be causing an issue with Django being able to understand the submission.

1 Like

Does it change if you add something to the action field, rather than a blank action=“”?

Hello Ken,

great! It was the enctype attribute from the form. When I submit a form with enctype=“” or with enctype=“multipart/form-data” it works.

Not with enctype=“text/plain”

Do you know the reason for this behavior, and is this correct?

Thank you very much!

Greetings
Suhel

Hello Astral-Weeks,

it makes no difference if I enter the URL or if I leave the action blank.

The reason for this problem was the enctype attribute. See my answer to Ken.

Best regards
Suhel

This appears to be proper behavior.

See the docs at HTMLFormElement: enctype property - Web APIs | MDN to see why.

1 Like

That’s it:

Yep, you got it.

Side note: For future reference, please do not post images of any text data. Code, templates, snippets from docs, scripts, output, error messages, etc should all be copied from the source text, and pasted into the body of your post, between lines of three backtick - ` characters as appropriate. Thanks!

1 Like