Why language is not changing with set_language url in Django? - django

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

Related

Django Debug Toolbar show queries from middleware

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.

You cannot add messages without installing django.contrib.messages.middleware.MessageMiddleware

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)

Add auth user in django admin interface: HTTP 403 error

I have a weird issue when I try to save a new user through the admin interface.
I get a 403 HTTP status code error.
I've changed nothing in the auth application.
Here are my middlewares:
MIDDLEWARE_CLASSES = (
'johnny.middleware.LocalStoreClearMiddleware',
'johnny.middleware.QueryCacheMiddleware',
#'django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
#'django.middleware.cache.FetchFromCacheMiddleware',
)
I've no idea where to look, or either have any idea of what could provocate this. Any clue is welcome.
Your user probably has not permissions to add new users. It's a normal behaviour to return 403 code in this case. View the doc, please: https://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.decorators.permission_required.
And (in this case) your user can have permission to delete users because it's the decoupled permissions.
You can view permissions of the user it: http://yoursite.com/admin/auth/user/{user_id}/ ( from superuser or user that can view permissions of other users).
Update. The author of the question found the decision: the situation was because of Apache settings (switching mod_security off fixed the problem). Unfortunately I have not deep knowledge about the module and I can't give more detailed information.

django post request data caching

hi have a template with a form and many inputs that pass some data trough a POST request to a view, that process them and send the result to another template. in the final template, if i use the browser back button to jump to the first view, i can see again old data. i refresh the page and i insert new data, i submit again but some old data remain when i see the final view. the problem remain even if i restart the debug server. how can i prevent it? it seems that there's some data-caching that i can solve only flushing browser cache. this is the view code: http://dpaste.com/640956/ and the first template code: http://dpaste.com/640960/
any idea?
tnx - luke
Is not django who populate form. Is cache navigator. You should switch off cache navigator. I use a custom middleware to do this:
from django.http import HttpResponse
class NoCacheMiddleware(object):
def process_response(self, request, response):
response['Pragma'] = 'no-cache'
response['Cache-Control'] = 'no-cache must-revalidate proxy-revalidate no-store'
return response
Remember to add middleware on settings.py:
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',
'ghap.utils.middleware.NoCacheMiddleware',
)
Maybe autocomplete="off" in the form tag can help you.
https://developer.mozilla.org/en/How_to_Turn_Off_Form_Autocompletion

Django - Losing Auth Session

I am with some trouble in Django...
After login I am losing auth session for some pages.
If I access "accounts/login/","accounts/logout/",""accounts/register/" the session always will be there, but if I access different page I cant access the user variable.
This is strange because I am using the same "base.html" for all pages and inside has the logic "if user.is_authenticated", how I said this condition is true just when I access pages that have "accounts" in the URL.
in the settings file I enabled theses three middleware:
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
Thanks
Just a guess here: are you including RequestContext in your context in the views that you cannot access user?
In other words, if you call generic views the RequestContext is automatically included but if you are using render_to_response() then you need to call it like this:
return render_to_response('template_name',
{ your context dict },
context_instance=RequestContext(request))