I am using Django Debug Toolbar to debug and optimize my website. I am also using some custom middleware to do things such as checking to see if a user is logged in and is allowed to access the url they are trying to view, querying ads, etc.
In this middleware, sometimes SQL queries are performed, but the queries don't show up under the 'queries' panel in DDT. Is there any way to get DDT to recognize and track middleware?
According to the documentation:
The order of MIDDLEWARE_CLASSES is important. You should include the
Debug Toolbar middleware as early as possible in the list. However, it
must come after any other middleware that encodes the response’s
content, such as GZipMiddleware.
The solution is to put debug_toolbar.middleware.DebugToolbarMiddleware before your custom middleware in MIDDLEWARE_CLASSES.
One of the place i found error is when I added a separate file debugtoolbar.py for all settings pertaining to enable debug_toolbar. I just imported this in my settings_local.py but it was calling somehow twice and it was not showing the queries.
As soon as I added a conditional statement to add
import os
import sys
from my_project.settings import INSTALLED_APPS, MIDDLEWARE_CLASSES
DEBUG_TOOLBAR_APPS_NAME = 'debug_toolbar'
if DEBUG_TOOLBAR_APPS_NAME not in INSTALLED_APPS:
INSTALLED_APPS += ( DEBUG_TOOLBAR_APPS_NAME, )
DEBUG_TOOLBAR_MIDDLEWARE = 'debug_toolbar.middleware.DebugToolbarMiddleware'
if DEBUG_TOOLBAR_MIDDLEWARE not in MIDDLEWARE_CLASSES:
MIDDLEWARE_CLASSES = ( DEBUG_TOOLBAR_MIDDLEWARE, ) + MIDDLEWARE_CLASSES
def custom_show_toolbar(request):
return True
DEBUG_TOOLBAR_CONFIG = {
'SHOW_TOOLBAR_CALLBACK': 'my_project.settings.custom_show_toolbar',
}
It started working all fine. Hope this will save someone's time.
Related
I added django-user-language-middleware package but it only change language when I manually change it at admin or DB.
When I use set_language link, it doesn't update language.
Before adding that middleware, it was working without any problem but I need to save language for user.
The middleware order:
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'user_language_middleware.UserLanguageMiddleware',
...
}
Wrote a simple custom view that change language of current user
I am new to Django.
I am trying to run an app and I need to add a new user to admin. The server is running. When I enter the info fir the new user and hit "save" I get the error below. I am using django-trunk.
MessageFailure at /admin/auth/user/add/
You cannot add messages without installing
django.contrib.messages.middleware.MessageMiddleware
Request Method: POST
Request URL: http://localhost:8000/admin/auth/user/add/
Django Version: 1.6.dev20130403090717
Exception Type: MessageFailure
Exception Value: You cannot add messages without installing django.contrib.messages.middleware.MessageMiddleware
Any ideas of what might be happening?
For me the problem was specific to unit testing. It turns out that some middleware won't work in some kinds of unit tests, more info here:
https://code.djangoproject.com/ticket/17971
and here:
Why don't my Django unittests know that MessageMiddleware is installed?
My solution was to just mock out the messages framework for those tests, there may be better solutions (the django test client?)
Check if you have django.contrib.messages in INSTALLED_APPS and django.contrib.messages.middleware.MessageMiddleware in MIDDLEWARE_CLASSES.
If you are running normal django code, you should add
django.contrib.messages.middleware.MessageMiddleware to your middlewares as others have suggested
If you are running a test case and using request factory then as #hwjp answered above, it's a bug (that won't be fixed). The request factory doesn't call the middlewares and developers don't intend to change this behaviour.
There is however a simple solution.
in your test settings file (i.e settings/test.py) add the following line
MESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage'
in your test code you can write code like this
request = RequestFactory().get("/")
# Add support django messaging framework
request._messages = messages.storage.default_storage(request)
and that's it. Passing this request object to any code that uses django messages will work without a problem.
Check if it is
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
instead of
MIDDLEWARE = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
Tuple name should be MIDDLEWARE_CLASSES
MIDDLEWARE_CLASSES depreciated https://docs.djangoproject.com/en/2.1/releases/1.10/#id3
2018 update
In django 2.0+ name in settings was changed.
Right now use MIDDLEWARE instead of MIDDLEWARE_CLASSES name of list in settings!
If the request is needed in tests, it can be mocked as suggested by #Ramast.
I found the solution mentioned in the bug ticket (closed, won't fix) to be helpful.
from django.contrib.messages.storage.fallback import FallbackStorage
from django.test import RequestFactory
def dummy_request():
"""Dummy request for testing purposes with message support."""
request = RequestFactory().get('/')
# Add support django messaging framework
setattr(request, 'session', 'session')
setattr(request, '_messages', FallbackStorage(request))
return request
Probably you put a wrong WSGI_request when usually called request as a parameter to add_message() method
I met the same error.
You have to notice the order of middleware in MIDDLEWARE_CLASSES.
Insert the corresponding middleware in the final.Like this,
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
Note the order arrangement.
If your issue is simulating these middlewares during unit testing, you can spoof this by writing a couple of little helpers:
def add_session_to_request(request: HttpRequest) -> HttpRequest:
"""Adds session support to a RequestFactory generated request."""
middleware = SessionMiddleware(get_response=lambda request: None)
middleware.process_request(request)
request.session.save()
return request
def add_messages_to_request(request: HttpRequest) -> HttpRequest:
"""Adds message/alert support to a RequestFactory generated request."""
request._messages = FallbackStorage(request)
return request
You can then call these in your test function at the point your request needs to have the middleware bound and just pass in the request you're using, which should keep your tests happy. :)
# To suppress the errors raised when triggering .messages through APIRequestFactory(),
# we need to bind both a session and messages storage on the fly
add_session_to_request(replacement_request)
add_messages_to_request(replacement_request)
I'm very new to Django and LDAP ... any help is is appreciated.
So i'm trying to setup and ldaps in Django. I'm trying to follow this (http://packages.python.org/django-auth-ldap/) instruction, but i have few questions ...
Where is AUTHENTICATION_BACKENDS located? So that i can add django_auth_ldap.backend.LDAPBackend
Where is AUTH_LDAP_SERVER_URI?
If i get the solutions to these i maybe able to figure out the rest ...
Thanks a lot for looking into this.
AUTHENTICATION_BACKENDS should be located in your settings.py. This is where almost all configuration is done.
For AUTH_LDAP_SERVER_URI, I think you need to add this as a global variable to your settings.py.
You may also take a quick look at the example configuration on the page you referred to.
EDIT
You are right, those variables are not present in the initial settings.py. You need to add the following to your settings.py:
# Keep ModelBackend around for per-user permissions and maybe a local
# superuser.
AUTHENTICATION_BACKENDS = (
'django_auth_ldap.backend.LDAPBackend',
'django.contrib.auth.backends.ModelBackend',
)
AUTH_LDAP_SERVER_URI = "ldap://ldap.example.com" # replace by the real URI
I have some problems with Django admin.
after syncdb, the result is:
Creating tables ...
Installing custom SQL ...
Installing indexes ...
No fixtures found.
What does this mean?
Anyway, when I visit the website admin panel http://www.example.com/admin/, I receive this message:
DoesNotExist at /admin/
Site matching query does not exist.
setting.py contains:
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
)
ur.py contains:
from django.conf.urls.defaults import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'rshd.views.home', name='home'),
# url(r'^rshd/', include('rshd.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)),
)
You don't really need the sites framework if you only run one site from the project, so the easiest fix would be to remove the following item from your INSTALLED_APPS and the error should go away:
'django.contrib.sites'
You can also re-create the missing Site object from shell. Run python manage.py shell and then:
from django.contrib.sites.models import Site
Site.objects.create(pk=1, domain='www.example.com', name='example.com')
You can fix this error if you are using django.contrib.sites without removing it by changing SITE_ID = 1 value in settings.py file.
It is happen to me when I changed domain name on my server, I deleted old domain name from http://mynewdomainname.com/admin/sites/site/ manually, and the old domain record in database has id = 1, also I added new domain name mynewdomainname.com and it is id was id = 2,
I just changed to SITE_ID = 2 and the error gone SITE_ID refers to current "pk" of active domain name you use as default.
In code:
>>> from django.contrib.sites.models import Site
>>> # get_current() came from SiteManager class manager,
>>> # see site-packages/django/contrib/sites/models.py
>>> current_site = Site.objects.get_current()
>>> print(current_site.pk)
2
>>> print(current_site.domain)
'http://mynewdomainname.com'
this happen after settings.py changed
SITE_ID = 2
Be careful about current domain id in django sites app.
The same problem also suddenly came to me, and you know there're many solutions. However, what's the reason of this sudden problem?
After dig in deeply, I found the reason is that, we ignored a step in the first syncdb action.
When you have your first syncdb, django will ask you to create a default account, if you don't input in this interactive show, that site object would not be created automatically.
So be careful of this. I'm using django 1.3.1, don't know whether the latest version has resolved this issue.
Since the above comments are pretty old and the syncdb command doesn't exist, and I don't want to remove django.contrib.sites, here's what worked for me:
Increment SITE_ID. I had SITE_ID = 1, changed it to SITE_ID = 2 and everything worked again.
Add SITE_ID = 1 in your settings.py
just fixed the issue by an another way:
I use PostgreSQL and Django 1.45...
as i removed the www.example.com Site and added a new www.xxx.com Site it was added as ID=2
'cause PostgreSQL doesn't go back in the ID numbers and the login and logout Django-Sites are somehow bound only to the ID=1 Site in your DB...
I went to my PostgreSQL DB and changed the ID of www.xxx.com to 1 and then I was able to see the login and logout Site again :)
btw. [yes, you just can remove the django.contrib.sites from your settings.py if you don't need it ^^ (but I haven't tried this one out in my case, with the ID number problem)]
hope it will work for further users! ;)
Yes change the SITE_IT=1 to SITE_ID=2 and everything is ok
Yes, the solution mentioned at the top can be (part of) the solution.
I've noticed however, that not only including django.contrib.sites without configuration can cause that problem, also including any site of
allauth (pip install django-allauth) might cause this problem if said package is not configured correctly.
(And allauth is as far as I've seen not configured correctly by default...)
Another thing you can do is simple if you get some error or just want to change site.
Download sqlitebrowser
open your sqlite.db
search for django_sites
change domain name and display name to whatever you want
Check your Window task manager and make sure that there is 1 process name 'python.exe' is running. If there are many, delete all of them then restart the server. This solution works for me.
I added a model to admin via admin.site.register, and it does not show up in admin. Since admin is so "It just works", I have no idea of how to debug this. Pointers?
After adding and registering your admin:
# app/admin.py
class YourModelAdmin(admin.ModelAdmin):
pass
admin.site.register(YourModel, YourModelAdmin)
Make sure your app is in your project settings.py:
# settings.py
INSTALLED_APPS = (
# other apps ...
'app',
)
Sync your project for that model if you have not done so already:
python manage.py syncdb
Restart your server, CTRL-C:
python manage.py runserver
In such a situation is also a good practice to check if the user logged in to the admin panel has rights to manage such a model. If they do then you could change your code to access the functions as root.
When in doubt, shut down server, syncdb, start server.
I have the experience, that sometimes after changing an admin.py the dev-sever won't be restarted. in that case touch settings.py helps.
I think the checklist in Thierry's answer is almost definitive, but make sure that urls.py contains admin.autodiscover() to load INSTALLED_APPS admin.py modules.
# urls.py
from django.conf.urls.defaults import *
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
('^admin/', include(admin.site.urls)),
)
More info in the django docs.
Have you added the application to your installed apps? That has happened to me both one and two times. :) Otherwise it would be useful for us to see the code to help you.
Also make sure there are no syntax errors in your admin.py or anything. That can cause an app to fail to be registered with the AdminSite.
I've faced the same problem, but it was a little tricky than yours.
Consider, that you have a project with, say, five or even more apps. For me it is more obvious to register all models in just one admin.py file, so I have decided to do it in one place - core directory. Of course, it was not an app, so none of models showed up on admin page.
comment out the some lines in urls.py see docs for more details
admin.autodiscover()
urlpatterns = patterns('',
('^admin/', include(admin.site.urls)),
)