Django: How to set default language in admin on login
-
05-10-2019 - |
Question
I'm saving an user's default language in his user profile and on login I want to set the admin's default language to it.
One possibility I was thinking of is using a middleware, but I think if I do it on process_request
I will not see an user object there since this is processed AFTER the middleware, so I could only set it after the next request!
Any solutions are highly appreciated!
Solution
The sad thing is Django doesn't send any signals on Login/Logout (apparently there's a ticket open for that at http://code.djangoproject.com/ticket/5612).
But looking around I found a rather simple and elegant solution for implementing signals on login/logout without touching Django's code: http://charlesleifer.com/blog/hooking-into-djangos-login-and-logout-two-approaches/
OTHER TIPS
You can do follow: In templates/admin/login.html
<script type="text/javascript">
$(function(){
$.ajax({
type : 'POST',
url : "{% url 'setLangueDefault' %}",
dataType : 'JSON',
success : function(data) {
//
}
});
});
</script>
In frontend/urls.py
urlpatterns = patterns('frontend.views',
...
url(r'^set-language-default/$', views.setLangueDefault, name='setLangueDefault'),
....
)
In frontend/views.py
from django.conf import settings
...
def setLangueDefault(request):
language = settings.LANGUAGE_CODE
if hasattr(request, 'session'):
if 'django_language' in request.session:
language = request.session['django_language']
if language:
request.session['django_language'] = language
if request.is_ajax():
message = {'status' : 0, 'info' : 'done'}
return JsonResponse(json.dumps(message))
return HttpResponseRedirect('/')
Note config default language in settings.py Exp: LANGUAGE_CODE = 'vi'