我们从Python开源项目中,提取了以下42个代码示例,用于说明如何使用django.utils.translation.LANGUAGE_SESSION_KEY。
def logout(request): """ Removes the authenticated user's ID from the request and flushes their session data. """ # Dispatch the signal before the user is logged out so the receivers have a # chance to find out *who* logged out. user = getattr(request, 'user', None) if hasattr(user, 'is_authenticated') and not user.is_authenticated(): user = None user_logged_out.send(sender=user.__class__, request=request, user=user) # remember language choice saved to session language = request.session.get(LANGUAGE_SESSION_KEY) request.session.flush() if language is not None: request.session[LANGUAGE_SESSION_KEY] = language if hasattr(request, 'user'): from django.contrib.auth.models import AnonymousUser request.user = AnonymousUser()
def logout(request): """ Removes the authenticated user's ID from the request and flushes their session data. """ # Dispatch the signal before the user is logged out so the receivers have a # chance to find out *who* logged out. user = getattr(request, 'user', None) if hasattr(user, 'is_authenticated') and not user.is_authenticated: user = None user_logged_out.send(sender=user.__class__, request=request, user=user) # remember language choice saved to session language = request.session.get(LANGUAGE_SESSION_KEY) request.session.flush() if language is not None: request.session[LANGUAGE_SESSION_KEY] = language if hasattr(request, 'user'): from django.contrib.auth.models import AnonymousUser request.user = AnonymousUser()
def setlang(request): """ Sets a user's language preference and redirects to a given URL or, by default, back to the previous page. """ next = request.REQUEST.get('next') if not is_safe_url(url=next, host=request.get_host()): next = request.META.get('HTTP_REFERER') if not is_safe_url(url=next, host=request.get_host()): next = '/' response = redirect(next) lang_code = request.REQUEST.get('language', None) if lang_code and check_for_language(lang_code): if hasattr(request, 'session'): request.session[LANGUAGE_SESSION_KEY] = lang_code else: response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code, max_age=settings.LANGUAGE_COOKIE_AGE, path=settings.LANGUAGE_COOKIE_PATH, domain=settings.LANGUAGE_COOKIE_DOMAIN) return response
def test_session_language(self): page = api.create_page("home", "nav_playground.html", "en", published=True) api.create_title('fr', "home", page) page.publish('fr') page.publish('en') response = self.client.get('/') self.assertEqual(response.status_code, 302) self.assertRedirects(response, '/en/') engine = import_module(settings.SESSION_ENGINE) store = engine.SessionStore() store.save() # we need to make load() work, or the cookie is worthless self.client.cookies[settings.SESSION_COOKIE_NAME] = store.session_key # ugly and long set of session session = self.client.session session[LANGUAGE_SESSION_KEY] = 'fr' session.save() response = self.client.get('/') self.assertEqual(response.status_code, 302) self.assertRedirects(response, '/fr/') self.client.get('/en/') self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], 'en') response = self.client.get('/') self.assertEqual(response.status_code, 302) self.assertRedirects(response, '/en/')
def post(self, request): form = self.form_class(data=request.POST) # NOTE: authenticate is already called internally in form.clean if form.is_valid(): username_or_email = request.POST['username'] password = request.POST['password'] # NOTE: authenticate is already called internally in form.clean so there is no need to verify the result user = authenticate(username=username_or_email, password=password) login(request, user) request.session[translation.LANGUAGE_SESSION_KEY] = user.language redirect_to = request.POST.get('next', request.GET.get('next', reverse('landing_page:home'))) redirect_to = (redirect_to if is_safe_url(redirect_to, request.get_host()) else reverse('landing_page:home')) if redirect_to == "": return HttpResponseRedirect(reverse("landing_page:home")) else: return HttpResponseRedirect(redirect_to) return render(request, 'registration/login.html', {'form': form})
def get_lang_from_session(request, supported): if hasattr(request, 'session'): lang_code = request.session.get(LANGUAGE_SESSION_KEY, None) if lang_code and lang_code in supported: return lang_code return None
def set_language(request): """ 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. """ next = request.POST.get('next', request.GET.get('next')) if not is_safe_url(url=next, host=request.get_host()): next = request.META.get('HTTP_REFERER') if not is_safe_url(url=next, host=request.get_host()): next = '/' response = http.HttpResponseRedirect(next) if request.method == 'POST': lang_code = request.POST.get(LANGUAGE_QUERY_PARAMETER) if lang_code and check_for_language(lang_code): next_trans = translate_url(next, lang_code) if next_trans != next: response = http.HttpResponseRedirect(next_trans) if hasattr(request, 'session'): request.session[LANGUAGE_SESSION_KEY] = lang_code # Always set cookie response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code, max_age=settings.LANGUAGE_COOKIE_AGE, path=settings.LANGUAGE_COOKIE_PATH, domain=settings.LANGUAGE_COOKIE_DOMAIN) return response
def activate_locale(self, request): """ Save language and timezone settings from profile into session. The settings are read by django middleware. """ request.session[LANGUAGE_SESSION_KEY] = str(self.language) request.session[settings.TIMEZONE_SESSION_KEY] = str(self.timezone)
def get(self, request, *args, **kwargs): current_language = get_language() request.session[LANGUAGE_SESSION_KEY] = current_language return super(MoviesListView, self).get(request, *args, **kwargs)
def process_response(self, request, response): language = get_language() if hasattr(request, 'session'): session_language = request.session.get(LANGUAGE_SESSION_KEY, None) if session_language and not session_language == language: request.session[LANGUAGE_SESSION_KEY] = language request.session.save() if settings.LANGUAGE_COOKIE_NAME in request.COOKIES and \ request.COOKIES[settings.LANGUAGE_COOKIE_NAME] == language: return response max_age = 365 * 24 * 60 * 60 # 10 years expires = datetime.datetime.utcnow() + datetime.timedelta(seconds=max_age) response.set_cookie(settings.LANGUAGE_COOKIE_NAME, language, expires=expires) return response
def user_time(request): try: stprofile = StProfile.objects.get(user=request.user) timezone.activate(stprofile.time_zone) request.session['django_timezone'] = stprofile.time_zone except: pass messages.success(request, _(u"You have successfully logged in as %s") % request.user.username) try: translation.activate(stprofile.language) request.session[translation.LANGUAGE_SESSION_KEY] = stprofile.language except: pass return HttpResponseRedirect(reverse('home'))
def get_language_from_request(request): # noqa complexity-16 """ Analyzes the request to find what language the user wants the system to show. Only languages listed in settings.LANGUAGES are taken into account. If the user requests a sublanguage where we have a main language, we send out the main language. If check_path is True, the URL path prefix will be checked for a language code, otherwise this is skipped for backwards compatibility. """ global DEVICE_LANGUAGE supported_lang_codes = get_languages() if hasattr(request, 'session'): lang_code = request.session.get(LANGUAGE_SESSION_KEY) if lang_code in supported_lang_codes and lang_code is not None and check_for_language(lang_code): return lang_code lang_code = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME) try: return get_supported_language_variant(lang_code) except LookupError: pass accept = request.META.get('HTTP_ACCEPT_LANGUAGE', '') for accept_lang, unused in parse_accept_lang_header(accept): if accept_lang == '*': break if not language_code_re.search(accept_lang): continue try: return get_supported_language_variant(accept_lang) except LookupError: continue try: if DEVICE_LANGUAGE is None: DEVICE_LANGUAGE = DeviceSettings.objects.get().language_id return get_supported_language_variant(DEVICE_LANGUAGE) except (DeviceSettings.DoesNotExist, LookupError): pass try: return get_supported_language_variant(settings.LANGUAGE_CODE) except LookupError: return settings.LANGUAGE_CODE
def get_language_from_request(request, check_path=False): """ Analyzes the request to find what language the user wants the system to show. Only languages listed in settings.LANGUAGES are taken into account. If the user requests a sublanguage where we have a main language, we send out the main language. If check_path is True, the URL path prefix will be checked for a language code, otherwise this is skipped for backwards compatibility. """ if check_path: lang_code = get_language_from_path(request.path_info) if lang_code is not None: return lang_code supported_lang_codes = get_languages() if hasattr(request, 'session'): lang_code = request.session.get(LANGUAGE_SESSION_KEY) if lang_code in supported_lang_codes and lang_code is not None and check_for_language(lang_code): return lang_code lang_code = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME) try: return get_supported_language_variant(lang_code) except LookupError: pass accept = request.META.get('HTTP_ACCEPT_LANGUAGE', '') for accept_lang, unused in parse_accept_lang_header(accept): if accept_lang == '*': break if not language_code_re.search(accept_lang): continue try: return get_supported_language_variant(accept_lang) except LookupError: continue try: return get_supported_language_variant(settings.LANGUAGE_CODE) except LookupError: return settings.LANGUAGE_CODE
def user_preference(request): current_user = User.objects.get(username=request.user.username) if request.method == 'POST': if request.POST.get('cancel_button'): messages.warning(request, _(u"Changing user settings canceled")) return HttpResponseRedirect(reverse('home')) else: errors = {} stprofile = StProfile.objects.get_or_create(user=current_user)[0] form_first_name=request.POST.get('first_name', '').strip() current_user.first_name = form_first_name form_last_name=request.POST.get('last_name', '').strip() current_user.last_name = form_last_name form_email=request.POST.get('email', '').strip() users_same_email = User.objects.filter(email=form_email) if len(users_same_email) > 0 and current_user.email != form_email: current_user.email = form_email errors['email'] = _(u"This email address is already in use." + " Please enter a different email address.") elif len(form_email) > 0: try: validate_email(form_email) except ValidationError: errors['email'] = _(u"Enter a valid email address") else: current_user.email = form_email form_language=request.POST.get('lang') if stprofile.language != form_language: stprofile.language = form_language translation.activate(form_language) request.session[translation.LANGUAGE_SESSION_KEY] = form_language form_time_zone=request.POST.get('time_zone') if stprofile.time_zone != form_time_zone: stprofile.time_zone = form_time_zone timezone.activate(form_time_zone) request.session['django_timezone'] = form_time_zone if errors: messages.error(request, _(u'Please, correct the following errors')) return render(request, 'students/user_preference.html', {'current_user': current_user, 'timezones': pytz.common_timezones, 'errors': errors}) current_user.save() stprofile.save() messages.success(request, _(u"User settings changed successfully")) return HttpResponseRedirect(reverse('home')) else: return render(request, 'students/user_preference.html', {'current_user': current_user, 'timezones': pytz.common_timezones})
def post(self, request, *args, **kwargs): self.object = self.get_object() # set language key request.session[translation.LANGUAGE_SESSION_KEY] = request.POST['language'] # if a new avatar image was set, save it as the 'old' one self.avatar_kwargs = {'old_avatar_name': self.object.avatar.name} # Changing the email address should not be possible without entering the correct password!! # Normally this is a check one want in the clean-methods of those forms, but there it is not possible to access # elements of other forms, so this is a dirty workaround. # TODO maybe it is possible to provide this error to the respective clean-functions username = self.kwargs.get('username') # this should make this situation TOCTOU-safe # in case it doesn't try to use select_for_update() with transaction.atomic(): # NOTE: this has to be part of the atomic block! current_user = get_user_model().objects.get(username=username) old_email = current_user.email forms = request.POST new_email = forms['email'] wrong_password = False if old_email != new_email: try: provided_password = forms['old_password'] except: provided_password = None if(provided_password is None or provided_password == "" or authenticate(username=username, password=provided_password) is None): wrong_password = True # NOTE: in this case we shall not call save (super) if wrong_password: messages.add_message(request, messages.ERROR, _('You can not change the email-address without entering the correct password.' + 'All changes have been discarded!')) # TODO copy elements? - this might be some pain because we have to split those elements on both forms return super(EditProfilePageView, self).get(request, *args, **kwargs) response = super(EditProfilePageView, self).post(request, *args, **kwargs) current_user = get_user_model().objects.get(username=username) if response.status_code == 200: messages.add_message(request, messages.ERROR, _('Something went wrong, one or more field credentials are not fulfilled')) else: messages.add_message(request, messages.SUCCESS, _('Profile successfully edited.')) return response