I've been programming a Django application for over a year now. I got the CSRF token working fine in the beginning and there haven't been any problems since. But now, it's suddenly stopped working, both locally and in my development environment despite pushing no changes to it. Does anyone know why this might be, and how I could fix it? I will note that I'm unable to see the csrfmiddlewaretoken being passed in the Network tab, per this post
Here is a list of everything I've tried:
from django.views.decorators.csrf import ensure_csrf_cookie
from django.views.decorators.csrf import csrf_protect
...
@ensure_csrf_cookie
@csrf_protect
def templateFunc(request):
ALLOWED_HOSTS = ['127.0.0.1', 'localhost', ".awsapprunner.com", "dev.org"]
CSRF_COOKIE_DOMAIN = ['127.0.0.1:8000', 'localhost:8000', 'dev.org']
CSRF_TRUSTED_ORIGINS=['http://127.0.0.1:8000', 'http://localhost:8000', 'https://dev.org']
CSRF_COOKIE_SECURE = False
#CSRF_COOKIE_SECURE = True
The form I'm sending doesn't require a user login, so there shouldn't be any issue with user credentials being out of sync. I'm also testing locally, so it's not a problem with AWS
I'm using Python 3.12.5 and Django 4.2.7. To my knowledge, these haven't changed in the time since my CSRF token was working
Based on your debugging, I have few suggestions:
In your setting.py, CSRF_COOKIE_DOMAIN
is a list of domains, but it should ideally be a string as per Django doc.
Ref: https://docs.djangoproject.com/en/4.2/ref/settings/#csrf-cookie-domain
If you are making any AJAX/Fetch XHR requestes then make sure CSRF token related header is included in request. And check if CSRF token is set in browser cookies.