Skip to content

Instantly share code, notes, and snippets.

@bmispelon
Created November 29, 2013 02:13
Show Gist options
  • Save bmispelon/7700702 to your computer and use it in GitHub Desktop.
Save bmispelon/7700702 to your computer and use it in GitHub Desktop.
Django's views.i18n.set_language view reimplemented using generic CBV
class SetLanguageMixin(object):
def post(self, request):
response = super(RedirectView, self).post(request)
lang_code = request.POST.get('language', None)
if lang_code and check_for_language(lang_code):
if hasattr(request, 'session'):
request.session['_language'] = lang_code
else:
response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code)
return response
class SetLanguageView(SetLanguageMixin, RedirectView):
"""
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.
Since this view changes how the user will see the rest of the site, it must
only be accessed as a POST request. If called as a GET request, it will
redirect to the page in the request (the 'next' parameter) without changing
any state.
"""
permanent = False
http_method_names = ['get', 'post']
def get_redirect_url(self):
urls = [
self.request.POST.get('next', self.request.GET.get('next')),
self.request.META.get('HTTP_REFERER'),
]
for next in urls:
if is_safe_url(next, host=self.request.get_host()):
return next
return '/'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment