Forums

CSRF Token not generating in URL

Hi, Despite my middleware being setup and calling the csrf token in my templates, the urls do not contain a randomly generated token - can anyone help - I have used this the exact same way <I believe> in other projects but cannot get this one to work.

Settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', #Csrf Middleware is added 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ]

html template

<form method="POST" action="/update/{{ComicInput.id}}" novlaidate enctype="multipart/form-data">{%csrf_token%} <table class="table table-striped"> @login_required(login_url="/login/") def edit(request, id): record = ComicInput.objects.get(pk = id) form = editform(request.POST or None, request.FILES or None, instance=record) if request.user == record.uid: return render(request, 'app/edit.html',{'form':form,"ComicInput":record}) else: raise PermissionDenied # import it from django.core.exceptions {{form}} </table> <input type="submit" value="Update"/> | <a href="{% url 'ComicInventory' %}"> View Collection</a> </form>

view.py

That code is adding the csrf token to the POST data in a request, not the URL. In general, CSRF tokens are only used for requests that include POST data, so they are not usually added to the get parameters in the request. In fact, I could not find anywhere in the Django documentation where it is even possible to add a CSRF token as a GET parameter.

Hi Glenn, I'm not using Get in my code, I'm using Post as per the extract above.

Kind Regards, John

Looks like you are missing {% csrf_token %} tag in your form. See https://docs.djangoproject.com/en/4.0/ref/csrf/#how-to-use-it