Commits

Alex Ulianytskyi committed ceb90e9

Added ``set_language`` view

Comments (0)

Files changed (1)

django_utils/views.py

 from django.http import HttpResponseRedirect
 from django.template import RequestContext
 from django.template import loader
+from django.utils.translation import check_for_language
 from django.utils.translation import ugettext
 from django.views.generic.create_update import apply_extra_context
 from django.views.generic.create_update import get_model_and_form_class
                                    " parameter to the generic view or define a get_absolute_url"
                                    " method on the Model.")
 def create_or_update_object(request, model=None, obj=None, object_id=None, slug=None,
-        slug_field='slug', template_name=None, template_loader=loader,
-        extra_context=None, post_save_redirect=None, login_required=False,
-        context_processors=None, template_object_name='object',
-        form_class=None, model_admin=None):
+                            slug_field='slug', template_name=None, template_loader=loader,
+                            extra_context=None, post_save_redirect=None, login_required=False,
+                            context_processors=None, template_object_name='object',
+                            form_class=None, model_admin=None):
     """
     Create or update object
 
     if obj is not None:
         populate_xheaders(request, response, model, getattr(obj, obj._meta.pk.attname))
     return response
+
+def set_language(request, lang_code):
+    """
+    Redirect to a given url while setting the chosen language in the
+    session or cookie. The url and the language code need to be
+    specified in the request parameters.
+    """
+    next = request.REQUEST.get('next', None)
+    if not next:
+        next = request.META.get('HTTP_REFERER', None)
+    if not next:
+        next = '/'
+    response = HttpResponseRedirect(next)
+    if lang_code and check_for_language(lang_code):
+        if hasattr(request, 'session'):
+            request.session['django_language'] = lang_code
+        else:
+            response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code)
+    return response