'Django app runs locally but I get CSRF verification failed on Heroku
Solution 1:[1]
The error message is fairly self-explanatory (please excuse typos as I can't copy from an image):
Origin checking failed - https://pacific-coast-78888.herokuapp.com does not match any trusted origins
The domain you are using is not a trusted origin for CSRF.
There is then a link to the documentation, which I suspect goes to the Django CSRF documentation, though the documentation for the CSRF_TRUSTED_ORIGINS
setting might be more useful:
A list of trusted origins for unsafe requests (e.g.
POST
).For requests that include the
Origin
header, Django’s CSRF protection requires that header match the origin present in theHost
header.
Look in your settings.py
for CSRF_TRUSTED_ORIGINS
and add https://pacific-coast-78888.herokuapp.com
to the list. If that setting doesn't already exist, simply add it:
CSRF_TRUSTED_ORIGINS = ["https://pacific-coast-78888.herokuapp.com"]
Solution 2:[2]
If Heroku uses django "4.x.x" version:
Then, if the error is as shown below:
Origin checking failed - https://example.com does not match any trusted origins.
Add this code below to "settings.py":
CSRF_TRUSTED_ORIGINS = ['https://example.com']
In your case, you got this error:
Origin checking failed - https://pacific-coast-78888.herokuapp.com does not match any trusted origins.
So, you need to add this code below to your "settings.py":
CSRF_TRUSTED_ORIGINS = ['https://pacific-coast-78888.herokuapp.com']
Solution 3:[3]
I was facing same error and simply downgraded my DjangoVersion==4.0.4 to DangoVersion==3.2.13. And it Work for me.
Solution 4:[4]
It appears you do not have your heroku address as a trusted origin in the setting.py file of your project, to do this, you can use corsheaders
pip install django-cors-headers
then in your settings.py file
INSTALLED_APPS = [
...
'corsheaders',
...
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
...
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware',
]
If you were not yet deployed you could add CORS_ORIGIN_ALLOW_ALL = True
but because you know where your app is deployed using a whitelist for the origins is a much better idea
CORS_ORIGIN_WHITELIST = (
'https://pacific-coast-78888.herokuapp.com',
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Chris |
Solution 2 | Kai - Kazuya Ito |
Solution 3 | Sandip |
Solution 4 | Jaime Ortiz |