Django Localhost CORS not working - python

I have a local Django setup as follows
Django Rest Framework:localhost:8000
AngularJS frontend:local apache running on http://localservername
I've installed django-cors-headers and in my settings.py, I've setup my
CORS_ORIGIN_WHITELIST = (
'http://localhost',
'localservername',
'http://localservername',
'127.0.0.1'
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
However, I get a No 'Access-Control-Allow-Origin' header is present on the requested resource. error whenever I hit any API that's served from the Rest Framework. If I set CORS_ORIGIN_ALLOW_ALL = True, then the API's work correctly but that's highly insecure for my server side data.
What do I have to change to fix this?

Here in this error the hint is clearly mentioning that it needs https://
HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com).
Moreover, it is also true that braces matters in django settings.
CORS_ORIGIN_WHITELIST = [
'https://localhost:3000'
]
And the above settings work fine.
While the same settings with different brackets won't work
CORS_ORIGIN_WHITELIST = (
'https://localhost:3000'
)

For me i used [] instead of ().
Also don't add a '/' at the end url.
Something like this
CORS_ORIGIN_WHITELIST = [
'http://localhost:3000'
]

I had the same problem. By browsing the django-cors-headers-code found my mistake was the following:
While a complete CORS-header looks like this (notice schema AND hostname):
Access-Control-Allow-Origin: https://example.com
The CORS_ORIGIN_WHITELIST setting wants it in a format that compares to urlparse.netloc (docs) of the Origin-header, which is only the host (possibly the port)
def origin_found_in_white_lists(self, origin, url):
return (
url.netloc in conf.CORS_ORIGIN_WHITELIST or
(origin == 'null' and origin in conf.CORS_ORIGIN_WHITELIST) or
self.regex_domain_match(origin)
)
While the RegEx-whitelist compares it against the complete Origin-header.
So the correct setting (as the example in the setup-manual correctly states, but not properly describes) would be:
CORS_ORIGIN_WHITELIST = (
'example.com',
)
Which can be a problem if you do not want your API to talk to the non-secure http-version of a website. Use the RegEx in that case.
Also note: during troubleshooting I found out that the CORS-header is completely absent if no match is found. Which means that absence of the header is not a sure indication of a complete malfunction of the middleware, but maybe just a misconfiguration.

As per http://www.w3.org/Security/wiki/Same_Origin_Policy, the requests should be from same port, scheme, and host to be considered as same origin. Here one of your server is in port 80 and the other one is on 8080.
An origin is defined by the scheme, host, and port of a URL. Generally
speaking, documents retrieved from distinct origins are isolated from
each other. For example, if a document retrieved from
http://example.com/doc.html tries to access the DOM of a document
retrieved from https://example.com/target.html, the user agent will
disallow access because the origin of the first document, (http,
example.com, 80), does not match the origin of the second document
(https, example.com, 443).

This works for me, Please check with this, it may help you to resolve your issue.
CORS_ORIGIN_WHITELIST = (
'http://localhost',
)

Braces matter for me,use [] instead of (),
I have verified in Django,
others I haven't checked.
Write Like This:
CORS_ORIGIN_WHITELIST=[
'https://localhost:3000'
]

CORS_ORIGIN_WHITELIST=[ 'https://localhost:3000' ] it works fine.

Writing like
CORS_ORIGIN_WHITELIST = [ 'https://localhost:3000' ]
worked fine for me.

Copy the whitelist code from the django-cors-headers documentation, and then just modify it:
CORS_ORIGIN_WHITELIST = [
"https://example.com",
"https://sub.example.com",
"http://localhost:8080",
"http://127.0.0.1:9000"
]
That will guarantee you that you didn't make any typos.

Make sure that not to add path /, like following:
CORS_ORIGIN_WHITELIST = (
'https://localhost:3000/'
)
Just add the following code instead.
CORS_ORIGIN_WHITELIST = [
'https://localhost:3000'
]

maybe braces matter
[] instead of ()
CORS_ORIGIN_WHITELIST = [
'http://localhost',
'localservername',
'http://localservername',
'127.0.0.1'
]
should work

I think the best way to do solve this error is :-
Type the URL in the browser, for eg :-
If you are running an angular app, then do,
ng serve
and type the URL given by "ng serve" command into the browser. for eg :-
localhost:4200
then, Copy the URL from the browser and paste as it is in the cors allowed host. eg :-
CORS_ALLOWED_ORIGINS = [
'http://localhost:4200',
]
Note :- Don't forget to Remove the last "/" sign from the URL, so instead of,
http://localhost:4200/
add this :- http://localhost:4200
And after this, you'll see no error.

I fixed this by fixing the order in:
INSTALLED_APPS = [
...
'corsheaders',
'image_cropping',
'easy_thumbnails',
...
'rest_framework',
...
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
]

install Django cors package
django-cors-headers
go to settings.py and add it to installed apps
INSTALLED_APPS = [
.....
'corsheaders',
]
add it to the middleware
MIDDLEWARE = [
........
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
]
Most important step
add this right below the middleware without a slash at the end
CORS_ORIGIN_WHITELIST = ['http://localhost:3000']

Related

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

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

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

Using django subdomain and it says localhost does not belong to the domain example.com

I'm using the Django Package django-subdomain, and I don't think I've configured it correctly.
Now that I'm trying to load data from the DB I'm getting this error in the terminal
The host localhost:8000 does not belong to the domain example.com, unable to identify the subdomain for this request
I don't have any references to example.com in my project.
Here's my subdomain config:
ROOT_URLCONF = 'creativeflow.urls'
# A dictionary of urlconf module paths, keyed by their subdomain.
SUBDOMAIN_URLCONFS = {
None: ROOT_URLCONF, # no subdomain, e.g. ``example.com``
'www': ROOT_URLCONF,
'blog': ROOT_URLCONF + '.blogs',
}
SITE_ID = 1
Middleware:
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'subdomains.middleware.SubdomainURLRoutingMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
My urls:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^posts/(?P<year>\d{4})/(?P<months>\d{2}|\w{3})/(?P<day>\d{2})',
BlogListView.as_view(paginate_by=25), name="blog-list-view"),
]
I'm not certain of what other config I need to let me use/develop with subdomains. What do I need to change so I can access the BlogListView at http://localhost:8000/posts/2016/07/09 ? Or better via the actual subdomain of blog.creativeflow.com/posts/2016/07/09 ? I suspect the latter is just a simple change to the windows equivalent of /etc/hosts/.
SITE = 1 will correspond to the default example.com set by django.contrib.site.
django.contrib.sites registers a post_migrate signal handler which creates a default site named example.com with the domain example.com. This site will also be created after Django creates the test database.
This is stored in the DB so there's no way to set this purely in config.
To set it in the DB, follow the steps here:
>>> from django.contrib.sites.models import Site
>>> one = Site.objects.all()[0]
>>> one.domain = 'myveryspecialdomain.com'
>>> one.name = 'My Special Site Name'
>>> one.save()
Then you can run python manage.py dumpdata sites which produces a JSON of the data you've just loaded. Then later load it using django-admin loaddata fixture [fixture ...]. Otherwise you can set it via the admin interface, under the Site app.
This will display as example.org before it's fixed:
Change these:
That should fix the issue.
Why have you set SITE_ID = 1?
From the Django Docs for django.contrib.site:
django.contrib.sites registers a post_migrate signal handler which creates a default site named example.com with the domain example.com. This site will also be created after Django creates the test database.
You need to specify the correct SITE_ID for your current site.
What do I need to change so I can access the BlogListView at
http://localhost:8000/posts/2016/07/09 ? Or better via the actual
subdomain of blog.creativeflow.com
I've set up my linode with subdomains pointed to different apps and sites. I did this by configuring NGINX webserver and uWSGI web app daemon in "emperor" mode.
To test django-subdomain locally this question on adding subdomains to localhost may help.

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