Django app runs locally but I get CSRF verification failed on Heroku - python

My app runs fine at heroku local but after deployed to Heroku, every time I try to login/register/login as admin, it returns this error shown below.
I have tried to put #csrf_exempt on profile views, but that didn't fix the issue.
What can I do?

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 the Host 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"]

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']

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',
)

Related

Unable to Login Django Admin after Update : Giving Error Forbidden (403) CSRF verification failed

I am encountering the error Forbidden (403) CSRF verification failed when trying to login into the Django Admin after updating the version of Django.
Also, there were no changes in the settings of Django.
The error can be seen in the below image:
I Already posted it on https://shriekdj.hashnode.dev/unable-to-login-django-admin-after-update-giving-error-forbidden-403-csrf-verification-failed-request-aborted.
This Issue can happen suddenly after updating to the newer version Of Django.
Details
Django Project Foundation team made some changes in security requirements for all Django Versions 4.0 and Above. They made it mandatory to create a list of URLs getting any type of form upload or POST request in project settings named as CSRF_TRUSTED_ORIGINS.
They did not update the details in the latest tutorial documentation, but they published the Changes Notes at https://docs.djangoproject.com/en/4.0/releases/4.0/#csrf-trusted-origins-changes-4-0.
First Solution
For localhost or 127.0.0.1.
Goto settings.py of your Django project and create a new list of URLs at last like given below
CSRF_TRUSTED_ORIGINS = ['http://*', 'https://*']
if You're running a project in localhost, then you should open all URLs here * symbol means all URLs. Also, http:// is mandatory.
Second Solution
This is also for Localhost and DEBUG=True.
Copy the list of ALLOWED_ORIGINS into CSRF_TRUSTED_ORIGINS as given below.
ALLOWED_ORIGINS = ['http://*', 'https://*']
CSRF_TRUSTED_ORIGINS = ALLOWED_ORIGINS.copy()
Third Solution
When deploying, you have to add URLs to allow form uploading ( making any POST request ).
I know this may be tricky and time-consuming but it's now mandatory.
Also, this is mandatory for Online IDEs also like Replit and Glitch.
Open the config file (most likely settings.py) and set the CSRF_TRUSTED_ORIGINS key as a shallow copy of the ALLOWED_HOSTS key which, in turn, should be set as recommended in the documentation.1
For example:
# -*- coding: utf-8 -*-
# For security consideration, please set to match the host/domain of your site, e.g., ALLOWED_HOSTS = ['.example.com'].
# Please refer https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts for details.
ALLOWED_HOSTS = ['.yourdomain.com', '.localhost', '127.0.0.1', '[::1]']
# Whether to use a secure cookie for the CSRF cookie
# https://docs.djangoproject.com/en/3.2/ref/settings/#csrf-cookie-secure
CSRF_COOKIE_SECURE = True
# The value of the SameSite flag on the CSRF cookie
# https://docs.djangoproject.com/en/3.2/ref/settings/#csrf-cookie-samesite
CSRF_COOKIE_SAMESITE = 'Strict'
CSRF_TRUSTED_ORIGINS = ALLOWED_HOSTS.copy()
(...)
1 The config file contains a link to the documentation of the ALLOWED_HOSTS key — right above that key. Surprise, surprise.

wrong behavior of uwsgi and CSRF_TRUSTED_ORIGINS in django [duplicate]

I am developing an application which the frontend is an AngularJS API that makes requests to the backend API developed in Django Rest Framework.
The frontend is on the domain: https://front.bluemix.net
And my backend is on the domain: https://back.bluemix.net
I am having problems making requests from the frontend API to the backend API. The error is this:
Error: CSRF Failed: Referer checking failed - https://front.bluemix.net does not match any trusted origins.
I am using CORS and I have already included the following lines in my settings.py in the Django backend API:
ALLOWED_HOSTS = []
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CSRF_TRUSTED_ORIGINS = ['https://front.bluemix.net/']
CORS_REPLACE_HTTPS_REFERER = True
CSRF_COOKIE_DOMAIN = 'bluemix.net'
CORS_ORIGIN_WHITELIST = (
'https://front.bluemix.net/',
'front.bluemix.net',
'bluemix.net',
)
Anyone knows how to solve this problem?
Django 4.0 and above
For Django 4.0 and above, CSRF_TRUSTED_ORIGINS must include scheme and host, e.g.:
CSRF_TRUSTED_ORIGINS = ['https://front.bluemix.net']
Django 3.2 and lower
For Django 3.2 and lower, CSRF_TRUSTED_ORIGINS must contain only the hostname, without a scheme:
CSRF_TRUSTED_ORIGINS = ['front.bluemix.net']
You probably also need to put something in ALLOWED_HOSTS...
If you are running Django 4.x, you need to change the syntax to include the schema as part of the value.
CSRF_TRUSTED_ORIGINS = ['front.bluemix.net']
to
CSRF_TRUSTED_ORIGINS = ['https://front.bluemix.net']
https://docs.djangoproject.com/en/dev/releases/4.0/#format-change
For anyone who follows this, if you have set CORS_ORIGIN_ALLOW_ALL to True, then you don't need to set the CORS_ORIGIN_WHITELIST variable anymore, as you are allowing every host already.
SOLUTION TO MY PROBLEM - it might help somebody
the problem we had was a peculiar one, we have a Client application sending requests using TokenAuthentication to another application, a CRM built using Django Admin and therefore using SessionAuthentication. When we opened the Django Admin application, the SessionMiddleware was creating automatically a session_id cookie for that domain. When opening the Client application and trying to perform a request, we got the following error:
Error: CSRF Failed: Referer checking failed - https://domainofthedjangoadminapp.com does not match any trusted origins.
That was only because the session_id cookie was already set in the browser and therefore, the request was made using SessionAuthentication instead of TokenAuthentication and failing.
Removing the cookie was obviously fixing the problem.
According to this documentation. https://docs.djangoproject.com/en/4.0/releases/4.0/#csrf-trusted-origins-changes
install cors-header by: doing
pip install django-cors-headers
Add corsheaders to you installed apps
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'MyApp',
'crispy_forms',
'corsheaders',
]
Add the corsheader Middleware to your middleware
MIDDLEWARE = [
'**corsheaders.middleware.CorsMiddleware**',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
4 Set the origin
CSRF_TRUSTED_ORIGINS = ['https://front.bluemix.net']
Apr, 2022 Update:
If your django version is "4.x.x":
python -m django --version
// 4.x.x
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 the similar error to above:
Error: CSRF Failed: Referer checking failed - https://front.bluemix.net does not match any trusted origins.
So, you need to add this code to your "settings.py":
CSRF_TRUSTED_ORIGINS = ['https://front.bluemix.net']
I was also facing this issue. Ensure that the domain name does not contain the trailing slash. Instead of
CSRF_TRUSTED_ORIGINS = ['https://front.bluemix.net/']
Change it to
CSRF_TRUSTED_ORIGINS = ['https://front.bluemix.net']

CSRF validation does not work on Django using HTTPS

I am developing an application which the frontend is an AngularJS API that makes requests to the backend API developed in Django Rest Framework.
The frontend is on the domain: https://front.bluemix.net
And my backend is on the domain: https://back.bluemix.net
I am having problems making requests from the frontend API to the backend API. The error is this:
Error: CSRF Failed: Referer checking failed - https://front.bluemix.net does not match any trusted origins.
I am using CORS and I have already included the following lines in my settings.py in the Django backend API:
ALLOWED_HOSTS = []
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CSRF_TRUSTED_ORIGINS = ['https://front.bluemix.net/']
CORS_REPLACE_HTTPS_REFERER = True
CSRF_COOKIE_DOMAIN = 'bluemix.net'
CORS_ORIGIN_WHITELIST = (
'https://front.bluemix.net/',
'front.bluemix.net',
'bluemix.net',
)
Anyone knows how to solve this problem?
Django 4.0 and above
For Django 4.0 and above, CSRF_TRUSTED_ORIGINS must include scheme and host, e.g.:
CSRF_TRUSTED_ORIGINS = ['https://front.bluemix.net']
Django 3.2 and lower
For Django 3.2 and lower, CSRF_TRUSTED_ORIGINS must contain only the hostname, without a scheme:
CSRF_TRUSTED_ORIGINS = ['front.bluemix.net']
You probably also need to put something in ALLOWED_HOSTS...
If you are running Django 4.x, you need to change the syntax to include the schema as part of the value.
CSRF_TRUSTED_ORIGINS = ['front.bluemix.net']
to
CSRF_TRUSTED_ORIGINS = ['https://front.bluemix.net']
https://docs.djangoproject.com/en/dev/releases/4.0/#format-change
For anyone who follows this, if you have set CORS_ORIGIN_ALLOW_ALL to True, then you don't need to set the CORS_ORIGIN_WHITELIST variable anymore, as you are allowing every host already.
SOLUTION TO MY PROBLEM - it might help somebody
the problem we had was a peculiar one, we have a Client application sending requests using TokenAuthentication to another application, a CRM built using Django Admin and therefore using SessionAuthentication. When we opened the Django Admin application, the SessionMiddleware was creating automatically a session_id cookie for that domain. When opening the Client application and trying to perform a request, we got the following error:
Error: CSRF Failed: Referer checking failed - https://domainofthedjangoadminapp.com does not match any trusted origins.
That was only because the session_id cookie was already set in the browser and therefore, the request was made using SessionAuthentication instead of TokenAuthentication and failing.
Removing the cookie was obviously fixing the problem.
According to this documentation. https://docs.djangoproject.com/en/4.0/releases/4.0/#csrf-trusted-origins-changes
install cors-header by: doing
pip install django-cors-headers
Add corsheaders to you installed apps
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'MyApp',
'crispy_forms',
'corsheaders',
]
Add the corsheader Middleware to your middleware
MIDDLEWARE = [
'**corsheaders.middleware.CorsMiddleware**',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
4 Set the origin
CSRF_TRUSTED_ORIGINS = ['https://front.bluemix.net']
Apr, 2022 Update:
If your django version is "4.x.x":
python -m django --version
// 4.x.x
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 the similar error to above:
Error: CSRF Failed: Referer checking failed - https://front.bluemix.net does not match any trusted origins.
So, you need to add this code to your "settings.py":
CSRF_TRUSTED_ORIGINS = ['https://front.bluemix.net']
I was also facing this issue. Ensure that the domain name does not contain the trailing slash. Instead of
CSRF_TRUSTED_ORIGINS = ['https://front.bluemix.net/']
Change it to
CSRF_TRUSTED_ORIGINS = ['https://front.bluemix.net']

Unable log in to the django admin page with a valid username and password

I can’t log in to the django admin page. When I enter a valid username and password, it just brings up the login page again, with no error messages
This question is in the django FAQ, but I've gone over the answers there and still can't get past the initial login screen.
I'm using django 1.4 on ubuntu 12.04 with apache2 and modwsgi.
I've confirmed that I'm registering the admin in the admin.py file, made sure to syncdb after adding INSTALLED_APPS.
When I enter the wrong password I DO get an error, so my admin user is being authenticated, just not proceeding to the admin page.
I've tried both setting SESSION_COOKIE_DOMAIN to the machine's IP and None. (Confirmed that the cookie domain shows as the machine's IP in chrome)
Also, checked that the user authenticates via the shell:
>>> from django.contrib.auth import authenticate
>>> u = authenticate(username="user", password="pass")
>>> u.is_staff
True
>>> u.is_superuser
True
>>> u.is_active
True
Attempted login using IE8 and chrome canary, both results in the same return to the login screen.
Is there something else I'm missing????
settings.py
...
MIDDLEWARE_CLASSES = (
'django.middleware.gzip.GZipMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.transaction.TransactionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.admin',
'django.contrib.staticfiles',
'django.contrib.gis',
'myapp.main',
)
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SESSION_SAVE_EVERY_REQUEST = True
SESSION_COOKIE_AGE = 86400 # sec
SESSION_COOKIE_DOMAIN = None
SESSION_COOKIE_NAME = 'DSESSIONID'
SESSION_COOKIE_SECURE = False
urls.py
from django.conf.urls.defaults import * ##UnusedWildImport
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^bin/', include('myproject.main.urls')),
(r'^layer/r(?P<layer_id>\d+)/$', "myproject.layer.views.get_result_layer"),
(r'^layer/b(?P<layer_id>\d+)/$', "myproject.layer.views.get_baseline_layer"),
(r'^layer/c(?P<layer_id>\d+)/$', "myproject.layer.views.get_candidate_layer"),
(r'^layers/$', "myproject.layer.views.get_layer_definitions"),
(r'^js/mapui.js$', "myproject.layer.views.view_mapjs"),
(r'^tilestache/config/$', "myproject.layer.views.get_tilestache_cfg"),
(r'^admin/', include(admin.site.urls)),
(r'^sites/', include("myproject.sites.urls")),
(r'^$', "myproject.layer.views.view_map"),
)
urlpatterns += staticfiles_urlpatterns()
Apache Version:
Apache/2.2.22 (Ubuntu) mod_wsgi/3.3 Python/2.7.3 configured
Apache apache2/sites-available/default:
<VirtualHost *:80>
ServerAdmin ironman#localhost
DocumentRoot /var/www/bin
LogLevel warn
WSGIDaemonProcess lbs processes=2 maximum-requests=500 threads=1
WSGIProcessGroup lbs
WSGIScriptAlias / /var/www/bin/apache/django.wsgi
Alias /static /var/www/lbs/static/
</VirtualHost>
<VirtualHost *:8080>
ServerAdmin ironman#localhost
DocumentRoot /var/www/bin
LogLevel warn
WSGIDaemonProcess tilestache processes=2 maximum-requests=500 threads=1
WSGIProcessGroup tilestache
WSGIScriptAlias / /var/www/bin/tileserver/tilestache.wsgi
</VirtualHost>
UPDATE
The admin page does proceed when using the development server via runserver so it seems like a wsgi/apache issue. Still haven't figured it out yet.
SOLUTION
The problem was that I had the settings file SESSION_ENGINE value set to 'django.contrib.sessions.backends.cache' without having the CACHE_BACKEND properly configured.
I've changed the SESSION_ENGINE to 'django.contrib.sessions.backends.db' which resolved the issue.
Steps to debug:
Make sure that your Database is synced
Double check that you have a django_session table
Try to authenticate
Do you see a record being created in the django_session table?
IF NOT
remove non-standard settings
AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',)
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SESSION_SAVE_EVERY_REQUEST = True
SESSION_COOKIE_AGE = 86400 # sec
SESSION_COOKIE_DOMAIN = None
SESSION_COOKIE_NAME = 'DSESSIONID'
SESSION_COOKIE_SECURE = False
Make sure that your Database is synced
Double check that you have a django_session table
Try to authenticate
Do you see a record being created in the django_session table?
Let me know if this turns up any useful debug.
Sample settings file: https://github.com/fyaconiello/Django-Blank-Bare-Bones-CMS/blob/master/dbbbcms/settings.py
>>> from django.contrib.auth import authenticate
>>> u = authenticate(username="user", password="pass")
>>> u.is_staff = True
>>> u.is_superuser = True
Is there something else I'm missing?
u.is_active should be True
I had this problem. The issue is that in production I set two variables to True that allowed me to connect to the site using https.
SESSION_COOKIE_SECURE and CSRF_COOKIE_SECURE should be set to False if you are developing on localhost http. Changing these two variables to False allowed me to sign into the admin site when developing locally.
I don't believe the admin password is stored in the settings.py file. It's created when you first syncdb. I am thinking you either skipped creating the superuser or just made a typo.
Try running in terminal at your projects root.:
python django-admin.py createsuperuser
That will allow you to retype your admin login. Also seen here https://docs.djangoproject.com/en/dev/ref/django-admin/
Did you try by creating the user with :
python manage.py createsuperuser
I have the same issue when I create the db on a test machine and migrate it to the deployment server...
We had a similar issue in our app and these might help:
Use cleanup command to clear older sessions from django_sessions
Check the cookie size in firefox(firebug) or chrome developer tools. Because messaging is enabled by default in admin(django.contrib.messages.middleware.MessageMiddleware), the cookie size sometimes get larger than 4096 bytes with multiple edits and deletes. One quick test is to delete the "message" cookie and see if you can login after that.
And we actually ended up switching to nginx/uwsgi route because of this and other memory related issues with apache. Haven't seen this repeated in nginx since.
After not being able to log in myself, I saw in the comment above someone mentioned about removing non-standard settings.
Adding this to my local settings solved it for me
SESSION_COOKIE_SECURE = False
sounds like a session problem because after the post you get redirected and immediately the system has forgotten that you logged in.
try the following:
check your session backend is working.
swap it with cache backend if you use db cache backend to check if transaction middleware is messing around.
try db backend and check if there are sessions stored in the db table
I'm not exactly sure, but the problem might be with your URL configuration, concretely in these two lines:
(r'^admin/', include(admin.site.urls)),
(r'^sites/', include("myproject.sites.urls")),
A longer time ago, I had trouble with browsing the admin of my Django project because a single URL configuration overwrote a part of the admin url. It seems that Django doesn't like it when you specify a custom URL configuration that contains elements which are also part of the admin URL. In your case, you have the app django.contrib.sites enabled in your settings.py. You can access the admin panel of this app by going to http://127.0.0.1:8000/admin/sites/. It might be that your URL configuration with r'^sites/' in it overrides a part of the admin url. Try renaming this specific URL configuration or disable django.contrib.sites in INSTALLED_APPS for testing purposes.
Please note that this is just an assumption. All I know is that Django's admin panel is a bit picky about URL configurations using similar names like its own URLs. I cannot test it myself at the moment. But maybe this helps you a bit.
Check that you have at least one site to work with.
>>> from django.contrib.sites.models import Site
>>> Site.objects.count()
(0.048) SELECT COUNT(*) FROM `django_site`; args=()
1
If you see 0 here - create one.
Checking some other articles on this topic, it could be related to sys.path. Can you check and compare sys.path when running the dev server and when running WSGI.
For some details, have a look this and that article. But I would check the sys.path first, before going into the details of this article.
Make sure your database user table having following entry is true:
is_staff => True (if exit).
is_active => True .
is_superuser => True.
This is not OP's issue, but I am posting this answer in the hopes someone may have gone down the same path as I and arrived at this question as a result.
I came back to an old codebase after a year and was denied access to the admin panel despite all of the usual checks passing (user is present, nothing looks incorrect in the database, all debug modes are on, etc). Unfortunately, I had forgotten that the admin sign in page was not at the usual /admin route, but rather at an alternate route. The /admin page was a fake sign in page that always resulted in a failed sign in.
This setup was created using the app django-admin-honeypot.
For me below settings worked on localhost
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
]
SESSION_COOKIE_DOMAIN = None
SESSION_ENGINE = 'django.contrib.sessions.backends.db'
Disclaimer: I cannot add comments yet, so I have to ask clarification here proposing a solution at the same time. Sorry for that.
Is the user logged-out immediately after logging-in? something like this issue
You can check it in many ways, I suggest to add a hook to the logout signal (you can put it in your models.py):
from django.contrib.auth.signals import user_logged_out
def alertme(sender, user, request, **kwargs):
print ("USER LOGGED OUT!") #or more sophisticate logging
user_logged_out.connect(alertme)
then try to log in and check if the message appears in your console. If it appears, then you have to check if you have a redirect or a customized template calling logout after login. Hope it helps you find the issue.
I had same problem and it was just solved after restarting server :
systemctl restart nginx
You can ensure, the created user has been flagged as Is_staff = True, I sometimes forget to flag this to allow users to login to django admin
I had a related issue where I'd try to log in and the page would hang before the socket would eventually be killed. It turned out that I was indeed being logged in, but one of the login signal processors was freezing.
Celery couldn't pass its asynchronous tasks to RabbitMQ because the RabbitMQ server wasn't able to start.
For me, I could not login to the admin page in firefox but could login in chrome.
The problem was that I had CSRF_COOKIE_PATH set in my settings.py.
Never use that. It does not not work properly on django 1.8.
What I did was to navigate manually to the url I wanted to visit.
So like: http://wildlifeapi.herokuapp.com/admin/ was returning the awful Heroku application error.
So what I did was to visit http://wildlifeapi.herokuapp.com/admin/api/animal/ and BINGO! it worked.
The funny thing is that it works well on my phone. It's probably a django redirection bug.
My issue was that My Admin Page was not loading and not working. Here is what I did:
pip uninstall django
pip install django==2.2
For more Detail Check Django Documentation.
For anyone who encountered this problem after upgrading Django, the problem could be that the signature of the authenticate function has changed at some point. If the signature doesn't match what's expected, the backend is just ignored. So make sure your custom authentication backend authenticate method looks like this:
class EmailUsernameAuthenticationBackend(ModelBackend):
def authenticate(self, request, username=None, password=None, **kwargs):
# ...
And NOT like this (without the request argument):
class EmailUsernameAuthenticationBackend(ModelBackend):
def authenticate(self, username=None, password=None, **kwargs):
A bit late for the party, but to me it was different and surprinsingly simpler: for whatever reason my superuser account was gone so, obviously, the solution was I had to create it again.
I'm 99% sure I had executed migrate and makemigrations a few times after having created my superuser, but go figure...
It took me about a whole hour to finally figure it out, however. None of the variables discussed here existed in my settings.py -and still don't to the present moment- (probably because it has been nearly 10 years, so things might have changed considerably), like SESSION_ENGINE, SESSION_COOKIE_DOMAIN, CACHE_BACKEND, django_session table...
Also, Django's FAQ on this subject mentions checking if my account is_active and is_staff, but unfortunately without ever mentioning how to do it.
For my case it is always the issue with SESSION_COOKIE_DOMAIN:
On local machine I set it like:
SESSION_COOKIE_DOMAIN = 'localhost'
On remote one, domain one, like:
SESSION_COOKIE_DOMAIN = 'yourdomainname.com'
In my case, I was not able to log in because I was using email in the place of username (which in my case was "admin") to try to log in. So do ensure you're using the right username and password to log in
Use some other virtual environment.it worked for me when i used conda environment.

django-debug-toolbar not showing up

I looked at other questions and can't figure it out...
I did the following to install django-debug-toolbar:
pip install django-debug-toolbar
added to middleware classes:
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
)
3 Added INTERNAL_IPS:
INTERNAL_IPS = ('174.121.34.187',)
4 Added debug_toolbar to installed apps
I am not getting any errors or anything, and the toolbar doesn't show up on any page, not even admin.
I even added the directory of the debug_toolbar templates to my TEMPLATE_DIRS
What is DEBUG set to? It won't load unless it's True.
If it's still not working, try adding '127.0.0.1' to INTERNAL_IPS as well.
UPDATE
This is a last-ditch-effort move, you shouldn't have to do this, but it will clearly show if there's merely some configuration issue or whether there's some larger issue.
Add the following to settings.py:
def show_toolbar(request):
return True
SHOW_TOOLBAR_CALLBACK = show_toolbar
That will effectively remove all checks by debug toolbar to determine if it should or should not load itself; it will always just load. Only leave that in for testing purposes, if you forget and launch with it, all your visitors will get to see your debug toolbar too.
For explicit configuration, also see the official install docs here.
EDIT(6/17/2015):
Apparently the syntax for the nuclear option has changed. It's now in its own dictionary:
def show_toolbar(request):
return True
DEBUG_TOOLBAR_CONFIG = {
"SHOW_TOOLBAR_CALLBACK" : show_toolbar,
}
Their tests use this dictionary.
Debug toolbar wants the ip address in request.META['REMOTE_ADDR'] to be set in the INTERNAL_IPS setting. Throw in a print statement in one of your views like such:
print("IP Address for debug-toolbar: " + request.META['REMOTE_ADDR'])
And then load that page. Make sure that IP is in your INTERNAL_IPS setting in settings.py.
Normally I'd think you would be able to determine the address easily by looking at your computer's ip address, but in my case I'm running the server in a Virtual Box with port forwarding...and who knows what happened. Despite not seeing it anywhere in ifconfig on the VB or my own OS, the IP that showed up in the REMOTE_ADDR key was what did the trick of activating the toolbar.
If everything else is fine, it could also be that your template lacks an explicit closing <body> tag—
Note: The debug toolbar will only display itself if the mimetype of the response is either text/html or application/xhtml+xml and contains a closing tag.
Docker
If you're developing with a Django server in a Docker container with docker, the instructions for enabling the toolbar don't work. The reason is related to the fact that the actual address that you would need to add to INTERNAL_IPS is going to be something dynamic, like 172.24.0.1.
Rather than trying to dynamically set the value of INTERNAL_IPS, the straightforward solution is to replace the function that enables the toolbar, in your settings.py, for example:
DEBUG_TOOLBAR_CONFIG = {
'SHOW_TOOLBAR_CALLBACK': lambda _request: DEBUG
}
This should also work for other dynamic routing situations, like Vagrant or Heroku.
Here are some more details for the curious. The code in django_debug_tool that determines whether to show the toolbar examines the value of REMOTE_ADDR like this:
if request.META.get('REMOTE_ADDR', None) not in INTERNAL_IPS:
return False
so if you don't actually know the value of REMOTE_ADDR due to your dynamic docker routing, the toolbar will not work. You can use the docker network command to see the dynamic IP values, for example docker network inspect my_docker_network_name
The current stable version 0.11.0 requires the following things to be true for the toolbar to be shown:
Settings file:
DEBUG = True
INTERNAL_IPS to include your browser IP address, as opposed to the server address. If browsing locally this should be INTERNAL_IPS = ('127.0.0.1',). If browsing remotely just specify your public address.
The debug_toolbar app to be installed i.e INSTALLED_APPS = (..., 'debug_toolbar',)
The debug toolbar middleware class to be added i.e. MIDDLEWARE_CLASSES = ('debug_toolbar.middleware.DebugToolbarMiddleware', ...). It should be placed as early as possible in the list.
Template files:
Must be of type text/html
Must have a closing </html> tag
Static files:
If you are serving static content make sure you collect the css, js and html by doing:
./manage.py collectstatic
Note on upcoming versions of django-debug-toolbar
Newer, development versions have added defaults for settings points 2, 3 and 4 which makes life a bit simpler, however, as with any development version it has bugs. I found that the latest version from git resulted in an ImproperlyConfigured error when running through nginx/uwsgi.
Either way, if you want to install the latest version from github run:
pip install -e git+https://github.com/django-debug-toolbar/django-debug-toolbar.git#egg=django-debug-toolbar
You can also clone a specific commit by doing:
pip install -e git+https://github.com/django-debug-toolbar/django-debug-toolbar.git#ba5af8f6fe7836eef0a0c85dd1e6d7418bc87f75#egg=django_debug_toolbar
I tried everything, from setting DEBUG = True, to settings INTERNAL_IPS to my client's IP address, and even configuring Django Debug Toolbar manually (note that recent versions make all configurations automatically, such as adding the middleware and URLs). Nothing worked in a remote development server (though it did work locally).
The ONLY thing that worked was configuring the toolbar as follows:
DEBUG_TOOLBAR_CONFIG = {
"SHOW_TOOLBAR_CALLBACK" : lambda request: True,
}
This replaces the default method that decides if the toolbar should be shown, and always returns true.
I have the toolbar working just perfect. With this configurations:
DEBUG = True
INTERNAL_IPS = ('127.0.0.1', '192.168.0.1',)
DEBUG_TOOLBAR_CONFIG = {'INTERCEPT_REDIRECTS': False,}
The middleware is the first element in MIDDLEWARE_CLASSES:
MIDDLEWARE_CLASSES = (
'debug_toolbar.middleware.DebugToolbarMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
I hope it helps
Add 10.0.2.2 to your INTERNAL_IPS on Windows, it is used with vagrant internally
INTERNAL_IPS = (
'10.0.2.2',
)
This should work.
I had the same problem and finally resolved it after some googling.
In INTERNAL_IPS, you need to have the client's IP address.
Another thing that can cause the toolbar to remain hidden is if it cannot find the required static files. The debug_toolbar templates use the {{ STATIC_URL }} template tag, so make sure there is a folder in your static files called debug toolbar.
The collectstatic management command should take care of this on most installations.
I know this question is a bit old, but today i installed django-toolbar with docker and came across with the same issue, this solved it for me
INTERNAL_IPS = ["127.0.0.1", "10.0.2.2"]
import socket
hostname, _, ips = socket.gethostbyname_ex(socket.gethostname())
INTERNAL_IPS += [".".join(ip.split(".")[:-1] + ["1"]) for ip in ips]
As i read in a comment, the issue is that docker uses a dynamic ip, to solve this we can get the ip from the code above
An addition to previous answers:
if the toolbar doesn't show up, but it loads in the html (check your site html in a browser, scroll down)
the issue can be that debug toolbar static files are not found (you can also see this in your site's access logs then, e.g. 404 errors for /static/debug_toolbar/js/toolbar.js)
It can be fixed the following way then (examples for nginx and apache):
nginx config:
location ~* ^/static/debug_toolbar/.+.(ico|css|js)$ {
root [path to your python site-packages here]/site-packages/debug_toolbar;
}
apache config:
Alias /static/debug_toolbar [path to your python site-packages here]/site-packages/debug_toolbar/static/debug_toolbar
Or:
manage.py collectstatic
more on collectstatic here: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#collectstatic
Or manualy move debug_toolbar folder of debug_toolbar static files to your set static files folder
I tried the configuration from pydanny's cookiecutter-django and it worked for me:
# django-debug-toolbar
MIDDLEWARE_CLASSES = Common.MIDDLEWARE_CLASSES + ('debug_toolbar.middleware.DebugToolbarMiddleware',)
INSTALLED_APPS += ('debug_toolbar',)
INTERNAL_IPS = ('127.0.0.1',)
DEBUG_TOOLBAR_CONFIG = {
'DISABLE_PANELS': [
'debug_toolbar.panels.redirects.RedirectsPanel',
],
'SHOW_TEMPLATE_CONTEXT': True,
}
# end django-debug-toolbar
I just modified it by adding 'debug_toolbar.apps.DebugToolbarConfig' instead of 'debug_toolbar' as mentioned in the official django-debug-toolbar docs, as I'm using Django 1.7.
django 1.8.5:
I had to add the following to the project url.py file to get the debug toolbar display. After that debug tool bar is displayed.
from django.conf.urls import include
from django.conf.urls import patterns
from django.conf import settings
if settings.DEBUG:
import debug_toolbar
urlpatterns += patterns('',
url(r'^__debug__/', include(debug_toolbar.urls)),
)
django 1.10: and higher:
from django.conf.urls import include, url
from django.conf.urls import patterns
from django.conf import settings
if settings.DEBUG:
import debug_toolbar
urlpatterns =[
url(r'^__debug__/', include(debug_toolbar.urls)),
] + urlpatterns
Also don't forget to include the debug_toolbar to your middleware.
The Debug Toolbar is mostly implemented in a middleware. Enable it in your settings module as follows:
(django newer versions)
MIDDLEWARE = [
# ...
'debug_toolbar.middleware.DebugToolbarMiddleware',
#
Old-style middleware:(need to have _CLASSES keywork in the Middleware)
MIDDLEWARE_CLASSES = [
# ...
'debug_toolbar.middleware.DebugToolbarMiddleware',
# ...
]
For me this was as simple as typing 127.0.0.1:8000 into the address bar, rather than localhost:8000 which apparently was not matching the INTERNAL_IPS.
In my case, it was another problem that hasn't been mentioned here yet: I had GZipMiddleware in my list of middlewares.
As the automatic configuration of debug toolbar puts the debug toolbar's middleware at the top, it only gets the "see" the gzipped HTML, to which it can't add the toolbar.
I removed GZipMiddleware in my development settings. Setting up the debug toolbar's configuration manually and placing the middleware after GZip's should also work.
In my case I just needed to remove the python compiled files (*.pyc)
Like you said I have configured everything said in documentation, still debug_toolbar was not showing up.
Then I tried it in Firefox, it worked fine.
Then from chrome, I inspect the webpage and change classname class="djdt-hidden". You can try changing it or removing it.
run manage.py collectstatic and repeat the above step
Actually you can skip steps 2 and 3, by editing
.djdt-hidden{ display: none;}
from path
debug_toolbar/static/debug_toolbar/css/toolbar.css
Add this two lines somewhere in settings.py
import mimetypes
mimetypes.add_type("application/javascript", ".js", True)
in urls.py
import debug_toolbar
urlpatterns += [ path('__debug__/', include(debug_toolbar.urls)),]
Use reference django debug toolbar installation
If it still doesn't working then,
create launch.json and mention different port number for debugging
`
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Django",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}\\manage.py",
"args": [
"runserver",
"9000",
],
"django": true
}
]
}
`
Important step: check your webpage/template is in proper format inorder to show debug_toolbar. use html boilerplate template to edit your page or add missing elements/tags like
<html></html>
<body></body>
<head><head>
etc to your django template or import a layout
This wasn't the case for this specific author but I just have been struggling with the Debug Toolbar not showing and after doing everything they pointed out, I found out it was a problem with MIDDLEWARE order. So putting the middleware early in the list could work. Mine is first:
MIDDLEWARE_CLASSES = (
'debug_toolbar.middleware.DebugToolbarMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'dynpages.middleware.DynpageFallbackMiddleware',
'utils.middleware.UserThread',
)
I got the same problem, I solved it by looking at the Apache's error log.
I got the apache running on mac os x with mod_wsgi
The debug_toolbar's tamplete folder wasn't being load
Log sample:
==> /private/var/log/apache2/dummy-host2.example.com-error_log <==
[Sun Apr 27 23:23:48 2014] [error] [client 127.0.0.1] File does not exist: /Library/WebServer/Documents/rblreport/rbl/static/debug_toolbar, referer: http://127.0.0.1/
==> /private/var/log/apache2/dummy-host2.example.com-access_log <==
127.0.0.1 - - [27/Apr/2014:23:23:48 -0300] "GET /static/debug_toolbar/css/toolbar.css HTTP/1.1" 404 234 "http://127.0.0.1/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:28.0) Gecko/20100101 Firefox/28.0"
I just add this line to my VirtualHost file:
Alias /static/debug_toolbar /Library/Python/2.7/site-packages/debug_toolbar/static/debug_toolbar
Of course you must change your python path
It works for me.
#urls.py
if settings.DEBUG:
from django.conf.urls.static import static
import debug_toolbar
import mimetypes
mimetypes.add_type("application/javascript", ".js", True)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns = [path('__debug__/', include(debug_toolbar.urls)), ] + urlpatterns
you have to make sure there is a closing tag in your templates.
My problem is that there is no regular html tags in my templates, I just display content in plain text. I solved it by inheriting every html file from base.html, which has a tag.
I had the same problem using Vagrant. I solved this problem by adding ::ffff:192.168.33.1 to the INTERNAL_IPS as below example.
INTERNAL_IPS = (
'::ffff:192.168.33.1',
)
Remembering that 192.168.33.10 is the IP in my private network in Vagrantfile.
I had this problem and had to install the debug toolbar from source.
Version 1.4 has a problem where it's hidden if you use PureCSS and apparently other CSS frameworks.
This is the commit which fixes that.
The docs explain how to install from source.
For anyone who is using Pycharm 5 - template debug is not working there in some versions. Fixed in 5.0.4, affected vesions - 5.0.1, 5.0.2
Check out issue
Spend A LOT time to find that out. Maybe will help someone
In the code I was working on, multiple small requests were made during handling of main request (it's very specific use case). They were requests handled by the same Django's thread. Django debug toolbar (DjDT) doesn't expect this behaviour and includes DjDT's toolbars to the first response and then it removes its state for the thread. So when main request was sent back to the browser, DjDT was not included in the response.
Lessons learned: DjDT saves it's state per thread. It removes state for a thread after the first response.
What got me is an outdated browser!
Noticed that it loads some stylesheets from debug toolbar and guessed it might be a front-end issue.
After many trial and error, this worked for me in Django=3.1
After writing all internal_ip, middleware, appending in url, put this code in settings.py at below
def show_toolbar(request):
return True
DEBUG_TOOLBAR_CONFIG = {
"SHOW_TOOLBAR_CALLBACK": show_toolbar,
'INSERT_BEFORE': '</head>'
}
Many of them suggested SHOW_TOOLBAR_CALLBACK, but in my case it only worked after added 'INSERT_BEFORE'
have same issue
after adding
urls.py
mimetypes.add_type("application/javascript", ".js", True)
urlpatterns = [...
and
DEBUG_TOOLBAR_CONFIG = {
'INTERCEPT_REDIRECTS': False,
'SHOW_TOOLBAR_CALLBACK': lambda request: True,
'SHOW_TEMPLATE_CONTEXT': True,
'INSERT_BEFORE': '</head>'
}
javascripts files added but all tags have class djdt-hidden and hidden
<div id="djDebug" class="djdt-hidden" dir="ltr" data-default-show="true">
i was using GoogleChrome
in FireFox bug was fixed and django toolbar icon appear
if you are using windows, it might be from your registery.
set HKEY_CLASSES_ROOT.js\Content Type to text/javascript instead of text/plain.

Categories

Resources