Django serving each app separately in each its port - python

I've got a very simple project running on Django (no models yet) and I need to do the following:
I have created 2 apps, 'Ebony' and 'Ivory' that need to communicate with each other through JSON messages (originally designed to run on different machines but for now one is good enough).
The problem is that the Django Debug server is just one process which runs in a specific port. What I want to do is make each 'App' listen to its own port on the same server and if possible under the same Django project. Is such a scenario possible? And if yes, how should I go about it?
Thanks in advance

This is possible, but not the way you're conceptualizing it. A Django app is one part of what runs on a given web server. Thus a Django project, which has one or more apps, runs as a part of one web server.
The solution is to run multiple instances of Django. Not sure how well this is going to work for you with the debug servers. You can run each server on its own port by giving it a parameter telling it where to open the port, for example:
./manage.py runserver 8000
runs a debug server on 127.0.0.1:8000, and
./manage.py runserver 8080
runs another debug server on 127.0.0.1:8080. Usually this is done in separate shells.
You will need to make sure that the INSTALLED_APPS setting on one of these has 'Ebony' in it, and the other has 'Ivory'. You will also need to figure out some way to tell each instance how to connect to the other (usually by specifying a root URL).
That said, later on you will need to figure out if your two apps will be sharing the same database. If so, make sure that both machines can get to it. If not, make sure the DATABASES value in settings.py is different for each one. If you're sharing the database, Django's sites framework can help you keep things straight in your models.
To have both running from the same project, you have to tell Django which one to run. I prefer to use an environment variable. This changes the above runserver commands to:
SHARD=Ebony ./manage.py runserver 8000
and
SHARD=Ivory ./manage.py runserver 8080
In your settings.py file, this variable can be accessed through os.environ. So, for example, for the INSTALLED_APPS setting to have different values for each shard, you write something like:
SHARD = os.environ["SHARD"]
# Apps common to all shards go here.
LOCAL_APPS = [
commonApp,
]
# Add apps specific to each shard.
if SHARD == "Ebony":
LOCAL_APPS += [
Ebony,
]
elif SHARD == "Ivory":
LOCAL_APPS += [
Ivory,
]
# Add them to the apps that aren't mine.
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.admin',
# ... omitted for brevity ...
'django_extensions',
'south',
'debug_toolbar',
) + LOCAL_APPS
By defining SHARD as a setting in this file, you avoid having to have all your code access the environment variable, and you confine the logic for setting SHARD to settings.py, in case you want to change it later. Your other Python files, if needed, can get the setting with from django.conf.settings import SHARD.
A similar mechanism can be used to give each shard its own DATABASES setting, too. And anything else in settings.py.
Then later in your urls.py file, you use that to pull in your apps' URLs:
from django.conf.urls import *
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'commonApp.views.get_homepage', name='home'),
url(r'^login$', 'django.contrib.auth.views.login', name="login"),
url(r'^logout$', 'django.contrib.auth.views.logout',
{"next_page": "/"}, name="logout"),
# Admin
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
)
# Auto-add the applications.
for app in settings.LOCAL_APPS:
urlpatterns += patterns('',
url(r'^{0}/'.format(app), include(app + '.urls', namespace=app)),
)
This means your apps need their own urls.py files, and your app URL names get prefixed with your app names. So if the app Ebony defines a URL pattern with name="index", you would get that URL in a template with {% url 'Ebony:index' %}.

Related

Trouble loading Django App after testing other Django App for several days? Always redirects to requested URL that doesn't exist?

Over the weekend I attended a hackathon, at which I created a Django app that ran on 127.0.0.1:8000/myapp/list on my local machine with
python manage.py runserver
Today, I tried to launch another Django app that I had made in the past for bug fixes and things, but when I ran manage.py runserver it keeps redirecting me to 127.0.0.1:8000/myapp/list, even though it's a totally separate app.
Anyone know how to resolve this issue?
urls.py for Django app that I'm trying to run:
from django.conf.urls import url
from TweeTest import views
urlpatterns = [
url(r'^$', views.view_home, name='home'),
url(r'^about/$', views.AboutPageView.as_view()),
url(r'^contact/$', views.ContactPageView.as_view()),
url(r'^result/$', views.view_tweet, name = 'result'),
]
urls.py for Django app I made over the weekend:
from django.conf.urls import include, url
from django.conf import settings
from django.conf.urls.static import static
from django.views.generic import RedirectView
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^myapp/', include('myproject.myapp.urls')),
url(r'^$', RedirectView.as_view(url='/myapp/list/', permanent=True)),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Is it something to do with the RedirectView line in the second urls.py?
I'm not sure why a totally different Django app is trying to connect to the same URL as the other one... seems strange.
If someone knows the answer to this, that would be greatly appreciated!
Thanks!
UPDATE:
When I try to connect to 127.0.0.1:8000 on incognito mode, it works fine. Could this mean it's a browser issue?
Davis
permanent=True sends a HTTP 301 Permanent redirect to the browser. Browsers tend to cache 301 responses very aggressively, meaning your web browser currently remembers that http://127.0.0.1:8000/ is a permanent redirect to http://127.0.0.1:8000/myapp/list/. Since your browser doesn't know that different Django apps might be running on 127.0.0.1:8000 at different times, it always follows the cached redirect.
You shouldn't use permanent=True unless you know what you are doing. While it can boost the performance on a high-traffic site, it is rarely necessary for low- to medium-traffic sites, and the permanent caching can be a real pain for developers.
Either clear your browser cache, run your Django test server on a different port, or use a different browser.
Have you tried using a different browser or clearing your browser history? This sounds like a browser issue to me.

Django project on two domains - limiting access to urls/views

I am working on django project.
It utilizes multiple small apps - where one of them is used for common things (common models, forms, etc).
I want to separate whole for project to two domains, i.g.:
corporatedomain.com and userportal.com
I want corporatedomain.com to use different urls, same for userportal.com.
Is that possible? If so, how can I do this? How should I configure my urls?
Maybe you can look at the Django Site Framework. From Django official documentation:
Django comes with an optional “sites” framework. It’s a hook for associating objects and functionality to particular Web sites, and it’s a holding place for the domain names and “verbose” names of your Django-powered sites.
You can use then this approach
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.contrib.sites.models import Site
current_site = Site.objects.get_current()
if 'userportal' in current_site.domain:
urlpatterns = patterns('',
url(r'', include('userapp.urls')),
url(r'^admin/', include(admin.site.urls)),
)
else:
urlpatterns = patterns('',
url(r'', include('corporateapp.urls')),
url(r'^admin/', include(admin.site.urls)),
)
You should add as many entries as you need to Site Table and add django.contrib.sites app in your INSTALLED_APP and also a SITE_ID variable to your settings bound with the correct site ID. Use SITE_ID = 1 when no domain info are available (for example in your development session). More info about SITE_ID in this post).
In my settings I use the following approach:
SITE_ID = os.environ.get('SITE_ID', 1)
where I have set the right SITE_ID variable in each of my enrivorments.
You will have separate settings file anyway so define different ROOT_URLCONF for each domain.
UPDATE: If you don't want to use different settings then you have to write the middleware which will change the request.urlconf attribute using the HTTP_HOST header. Here is the example of such middleware.

Django production - No db table load in admin

I'm building a Django app and now I'm in production. I have this problem: after performing manage.py syncdb (all it's ok) I go into admin and I can not find the models tables . My admin.py file is present and this is my file url.py:
from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'stambol.views.home', name='home'),
# url(r'^stambol/', include('stambol.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
Where is the problem?
Permissions
First off, make sure you have permission to edit the missing models. It's common to be developing with a superuser account, and then to test your production deployment with a different non-superuser account. If you don't have at least read permission, the class won't be listed at all in the admin.
I think this is the most likely cause, but I will leave the rest since I had already written it.
Discovering your admin registrations:
One notable difference between runserver and a production server is that when you run runserver, it imports all your models.py files and validates the models. This does not happen in production, so if you register your models with the admin inside models.py you need to be sure to import that file so that code runs. You could do so in your main url conf.
The preferable solution is to do your registration in per-app admin.py files so they are picked up by autodiscover.
Settings:
You do need admin listed in installed apps, as #Pratik says. It also has some dependencies, as mentioned here. Installed apps should contain at least this:
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions'
'django.contrib.messages',
'django.contrib.admin',
#...
'myapp',
#...
]
Make sure the dir containing your app myapp is in your python path, so that myapp is picked up by autodiscover. This is working correctly for you already, or else you would get something like ImportError: No module named myapp.
Restarting the server:
Finally, just to recap what is buried deep within comments, you can restart your production server after making any code changes by touching your wsgi file: touch wsgi.py. Use tab-completion when you do this to be sure you're touching the existing wsgi file and not creating a new one thanks to a typo or some such. The wsgi file you're touching should contain something like this:
...
# tell django to find settings at APPS_DIR/mainsite/settings.py'
os.environ['DJANGO_SETTINGS_MODULE'] = 'mainsite.settings'
# hand off to the wsgi application
application = WSGIHandler()
Still broken?
If things still aren't working as expected, think farther outside the box. Keeping in mind that you're new to your production environment, is it possible some other code besides your own is being served up? Make some obvious change to a front-end page, restart the server, and see if it works. This is just a shot in the dark, of course.
from django import admin
from example.models import YourModel
admin.site.register(YourModel)
# or
class ModelAdmin(admin.ModelAdmin):
pass
admin.site.register(YourModel, YourModelAdmin)
This should do the trick
Make sure you have the below removed as comments inside INSTALLED_APPS in settings.py. Then run ./manage.py syncdb again. They should like as shown below without the # in front of them
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
'django.contrib.admindocs',

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.

django: admin site not formatted

I have a mostly entirely plain django project, with no adding of my own media or customization of the admin interface in any way. Running the server with python manage.py runserver results in a nicely-formatted admin interface. Running the server with gunicorn_django does not. Why is this the case, and how can I fix it?
It's definitely an issue of not finding the css files, but where are they stored? I never configured this, and the MEDIA_ROOT setting is ''.
EDIT: I just want to know how django-admin serves the non-existent admin files... and how can I get gunicorn_django to do the same?
If you use contrib.static, you have to execute a collectstatic command to get all the app-specific static files (including admin's own) into the public directory that is served by gunicorn.
I've run into this problem too (because I do some development against gunicorn), and here's how to remove the admin-media magic and serve admin media like any other media through urls.py:
import os
import django
...
admin_media_url = settings.ADMIN_MEDIA_PREFIX.lstrip('/') + '(?P<path>.*)$'
admin_media_path = os.path.join(django.__path__[0], 'contrib', 'admin', 'media')
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^' + admin_media_url , 'django.views.static.serve', {
'document_root': admin_media_path,
}, name='admin-media'),
...
)
Also: http://djangosnippets.org/snippets/2547/
And, of course, #include <production_disclaimer.h>.
I think the easiest way is to add alias to nginx (are you using one?!) configuration file:
location /static/admin/ {
alias /<path_to_your_admin_static_files>/;
}
it worked immediately for me
Ok, got it. Just had to add this line to settings.py:
MEDIA_ROOT = '/home/claudiu/server/.virtualenv/lib/python2.5/site-packages/django/contrib/admin/media/'
David Wolever's answer was close, for my installation, but I think some paths may have changed in newer django. In particular I set
admin_media_path = os.path.join(django.__path__[0], 'contrib', 'admin', 'static', 'admin')
and in urlpatterns added:
url(r'^static/admin/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': admin_media_path,
}),
based on info found here: https://docs.djangoproject.com/en/dev/howto/static-files/
works for me, but more "magical" than I like.

Categories

Resources