def get_language_from_request(request, current_page=None): from cms.models import Page """ Return the most obvious language according the request """ if settings.CMS_DBGETTEXT: return get_default_language() language = request.REQUEST.get('language', None) if language: if not language in dict(settings.CMS_LANGUAGES).keys(): language = None if language is None: language = getattr(request, 'LANGUAGE_CODE', None) if language: if not language in dict(settings.CMS_LANGUAGES).keys(): language = None # TODO: This smells like a refactoring oversight - was current_page ever a page object? It appears to be a string now if language is None and isinstance(current_page, Page): # in last resort, get the first language available in the page languages = current_page.get_languages() if len(languages) > 0: language = languages[0] if language is None: # language must be defined in CMS_LANGUAGES, so check first if there # is any language with LANGUAGE_CODE, otherwise try to split it and find # best match language = get_default_language() return language
def get_absolute_url(self, language=None): """ Given a thing object, return its URL. If language fallbacks are configured, then this should respect them. However, we should **never** try to do anything with the ``redirect_on_fallback`` settings in CMS and Parler here. That responsibility lies in the views. Essentially, if a caller provides an object that has a valid **active** language, then this will return a valid URL, not NoReverseMatch. However, if the caller attempts to request the URL, but the object does not have an **active** language translation, this may indeed, return a NoReverseMatch. :param language: The *desired* language. :return: The URL in the desired language, or a fallback, if configured. """ if not language: language = get_current_language() or get_default_language() slug, language = self.known_translation_getter( 'slug', None, language_code=language) kwargs = {'slug': slug} with override(language): return reverse('things:thing-detail', kwargs=kwargs)
def get_language_from_request(self, request): prefix = has_lang_prefix(request.path_info) lang = None if prefix: request.path = "/" + "/".join(request.path.split("/")[2:]) request.path_info = "/" + "/".join( request.path_info.split("/")[2:]) t = prefix if t in settings.CMS_FRONTEND_LANGUAGES: lang = t if not lang: languages = [] for frontend_lang in settings.CMS_FRONTEND_LANGUAGES: languages.append((frontend_lang, frontend_lang)) with SettingsOverride(LANGUAGES=languages): lang = translation.get_language_from_request(request) if not lang: lang = get_default_language() old_lang = None if hasattr(request, "session") and request.session.get( "django_language", None): old_lang = request.session["django_language"] if not old_lang and hasattr(request, "COOKIES") and request.COOKIES.get( settings.LANGUAGE_COOKIE_NAME, None): old_lang = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME) if old_lang != lang: if hasattr(request, 'session'): request.session['django_language'] = lang return lang
def get_language_from_request(self, request): changed = False prefix = has_lang_prefix(request.path_info) if prefix: request.path = "/" + "/".join(request.path.split("/")[2:]) request.path_info = "/" + "/".join( request.path_info.split("/")[2:]) t = prefix if t in SUPPORTED: lang = t if (hasattr(request, "session") and request.session.get("django_language", None) != lang): request.session["django_language"] = lang changed = True else: lang = translation.get_language_from_request(request) if not changed: if hasattr(request, "session"): lang = request.session.get("django_language", None) if lang in SUPPORTED and lang is not None: return lang elif "django_language" in request.COOKIES.keys(): lang = request.COOKIES.get("django_language", None) if lang in SUPPORTED and lang is not None: return lang if not lang: lang = translation.get_language_from_request(request) lang = get_default_language(lang) return lang
def _create_blog(self, options): default_language = get_default_language() languages = get_language_list() activate(default_language) try: blog_page = Page.objects.get( application_namespace=APP_NAMESPACE, publisher_is_draft=True, site=self.site, ) except Page.DoesNotExist: self.stdout.write("Create new blog AppHook page.") blog_page = create_page( title=_("blog"), template=options["template"], language=settings.LANGUAGE_CODE, apphook=BLOG_APP_HOOK, apphook_namespace=APP_NAMESPACE, in_navigation=True, ) else: self.stdout.write("Use existing blog AppHook page.") placeholder, created = Placeholder.objects.get_or_create(slot=PLACEHOLDER_SLOT) if created: self.stdout.write("New placeholder for blog page created.") placeholder.save() else: self.stdout.write("Use existing placeholder for blog page.") for language in languages: activate(language) if language != default_language: if Title.objects.filter(language=language, page=blog_page).exists(): self.stdout.write("Use existing title in %r" % language) else: self.stdout.write("Create title in %r" % language) create_title(language=language, title=_("blog"), page=blog_page) for plugin_type in PLUGIN_TYPES: queryset = CMSPlugin.objects.filter( placeholder=placeholder, plugin_type=plugin_type, language=language ) if queryset.exists(): self.stdout.write("Use existing plugin %r in %r" % (plugin_type, language)) else: self.stdout.write("Create plugin %r in %r" % (plugin_type, language)) add_plugin(placeholder, plugin_type, language=language) # self.stdout.write("publish placeholder in language: %r" % language) # placeholder.publish(request=None, language=language, force=True) self.stdout.write("publish blog page in language: %r" % language) blog_page.publish(language)
def add_wizard_button(self): from cms.wizards.wizard_pool import entry_choices title = _("Create") try: page_pk = self.page.pk except AttributeError: page_pk = '' user = getattr(self.request, "user", None) disabled = user and hasattr(self, "page") and len( list(entry_choices(user, self.page))) == 0 lang = get_language_from_request( self.request, current_page=self.page) or get_default_language() url = '{url}?page={page}&language={lang}&edit'.format( url=reverse("cms_wizard_create"), page=page_pk, lang=lang, ) self.toolbar.add_modal_button(title, url, side=self.toolbar.RIGHT, disabled=disabled, on_close=REFRESH_PAGE)
def get_language_from_request(request, current_page=None): """ Return the most obvious language according the request """ language = request.REQUEST.get('language', None) site_id = current_page.site_id if current_page else None if language: if not language in get_language_list(site_id): language = None if language is None: language = getattr(request, 'LANGUAGE_CODE', None) if language: if not language in get_language_list(site_id): language = None if language is None and current_page: # in last resort, get the first language available in the page languages = current_page.get_languages() if len(languages) > 0: language = languages[0] if language is None: # language must be defined in CMS_LANGUAGES, so check first if there # is any language with LANGUAGE_CODE, otherwise try to split it and find # best match language = get_default_language(site_id=site_id) return language
def get_language_from_request(self,request): changed = False prefix = has_lang_prefix(request.path_info) pages_root = urllib.unquote(reverse("home")) if prefix: request.path = request.path.split("/") del request.path[pages_root.count('/')] request.path = "/".join(request.path) request.path_info = "/" + "/".join(request.path_info.split("/")[2:]) t = prefix if t in SUPPORTED: lang = t if hasattr(request, "session"): request.session["django_language"] = lang changed = True else: lang = translation.get_language_from_request(request) if not changed: if hasattr(request, "session"): lang = request.session.get("django_language", None) if lang in SUPPORTED and lang is not None: return lang elif "django_language" in request.COOKIES.keys(): lang = request.COOKIES.get("django_language", None) if lang in SUPPORTED and lang is not None: return lang if not lang: lang = translation.get_language_from_request(request) lang = get_default_language(lang) return lang
def get_language_from_request(self, request): changed = False prefix = has_lang_prefix(request.path_info) pages_root = urllib.unquote(reverse("pages-root")) if prefix: request.path = request.path.split("/") del request.path[pages_root.count('/')] request.path = "/".join(request.path) request.path_info = "/" + "/".join( request.path_info.split("/")[2:]) t = prefix if t in SUPPORTED: lang = t if hasattr(request, "session"): request.session["django_language"] = lang changed = True else: lang = translation.get_language_from_request(request) if not changed: if hasattr(request, "session"): lang = request.session.get("django_language", None) if lang in SUPPORTED and lang is not None: return lang elif "django_language" in request.COOKIES.keys(): lang = request.COOKIES.get("django_language", None) if lang in SUPPORTED and lang is not None: return lang if not lang: lang = translation.get_language_from_request(request) lang = get_default_language(lang) return lang
def get_absolute_url(self, language=None): """ Given a thing object, return its URL. If language fallbacks are configured, then this should respect them. However, we should **never** try to do anything with the ``redirect_on_fallback`` settings in CMS and Parler here. That responsibility lies in the views. Essentially, if a caller provides an object that has a valid **active** language, then this will return a valid URL, not NoReverseMatch. However, if the caller attempts to request the URL, but the object does not have an **active** language translation, this may indeed, return a NoReverseMatch. :param language: The *desired* language. :return: The URL in the desired language, or a fallback, if configured. """ if not language: language = get_current_language() or get_default_language() slug, language = self.known_translation_getter('slug', None, language_code=language) kwargs = {'slug': slug} with override(language): return reverse('things:thing-detail', kwargs=kwargs)
def get_language_from_request (self,request): supported = dict(settings.LANGUAGES) #lang = settings.LANGUAGE_CODE langs = "|".join(map(lambda l: l[0], settings.LANGUAGES)) check = re.match(r"^/(%s)/.*" % langs, request.path_info) changed = False if check is not None: request.path = "/" + "/".join(request.path.split("/")[2:]) request.path_info = "/" + "/".join(request.path_info.split("/")[2:]) t = check.group(1) if t in supported: lang = t if hasattr(request, "session"): request.session["django_language"] = lang else: request.set_cookie("django_language", lang) changed = True else: lang = translation.get_language_from_request(request) if not changed: if hasattr(request, "session"): lang = request.session.get("django_language", None) if lang in supported and lang is not None: return lang elif "django_language" in request.COOKIES.keys(): lang = request.COOKIES.get("django_language", None) if lang in supported and lang is not None: return lang if not lang: lang = translation.get_language_from_request(request) lang = get_default_language(lang) return lang
def get_language_from_request(self, request): prefix = has_lang_prefix(request.path_info) lang = None if prefix: request.path = "/" + "/".join(request.path.split("/")[2:]) request.path_info = "/" + "/".join(request.path_info.split("/")[2:]) t = prefix if t in settings.CMS_FRONTEND_LANGUAGES: lang = t if not lang: languages = [] for frontend_lang in settings.CMS_FRONTEND_LANGUAGES: languages.append((frontend_lang,frontend_lang)) with SettingsOverride(LANGUAGES=languages): lang = translation.get_language_from_request(request) if not lang: lang = get_default_language() old_lang = None if hasattr(request, "session") and request.session.get("django_language", None): old_lang = request.session["django_language"] if not old_lang and hasattr(request, "COOKIES") and request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME, None): old_lang = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME) if old_lang != lang: if hasattr(request, 'session'): request.session['django_language'] = lang return lang
def get_language_from_request(self, request): changed = False prefix = has_lang_prefix(request.path_info) if prefix: request.path = "/" + "/".join(request.path.split("/")[2:]) request.path_info = "/" + "/".join(request.path_info.split("/")[2:]) t = prefix if t in SUPPORTED: lang = t if (hasattr(request, "session") and request.session.get("django_language", None) != lang): request.session["django_language"] = lang changed = True else: lang = translation.get_language_from_request(request) if not changed: if hasattr(request, "session"): lang = request.session.get("django_language", None) if lang in SUPPORTED and lang is not None: return lang elif "django_language" in request.COOKIES.keys(): lang = request.COOKIES.get("django_language", None) if lang in SUPPORTED and lang is not None: return lang if not lang: lang = translation.get_language_from_request(request) lang = get_default_language(lang) return lang
def render_placeholder(placeholder, context_to_copy, name_fallback="Placeholder"): """ Renders plugins for a placeholder on the given page using shallow copies of the given context, and returns a string containing the rendered output. """ from cms.plugins.utils import get_plugins context = context_to_copy context.push() request = context['request'] lang = get_language_from_request(request) page = get_page_from_placeholder_if_exists(placeholder) if page: template = page.template else: template = None plugins = [plugin for plugin in get_plugins(request, placeholder, lang)] if (len(plugins)==0 and placeholder and lang != get_default_language() and get_placeholder_conf("language_fallback", placeholder.slot, template, False)): fallbacks = get_fallback_languages(lang) for l in fallbacks: plugins = [plugin for plugin in get_plugins(request, placeholder, l)] if plugins: break # Add extra context as defined in settings, but do not overwrite existing context variables, # since settings are general and database/template are specific # TODO this should actually happen as a plugin context processor, but these currently overwrite # existing context -- maybe change this order? slot = getattr(placeholder, 'slot', None) extra_context = {} if slot: extra_context = get_placeholder_conf("extra_context", slot, template, {}) for key, value in extra_context.items(): if not key in context: context[key] = value content = [] # Prepend frontedit toolbar output if applicable edit = False toolbar = getattr(request, 'toolbar', None) if (getattr(toolbar, 'edit_mode', False) and (not page or page.has_change_permission(request))): edit = True if edit: from cms.middleware.toolbar import toolbar_plugin_processor processors = (toolbar_plugin_processor,) else: processors = None content.extend(render_plugins(plugins, context, placeholder, processors)) content = "".join(content) if edit: content = render_placeholder_toolbar(placeholder, context, content, name_fallback) context.pop() return content
def render_placeholder(placeholder, context_to_copy, name_fallback="Placeholder"): """ Renders plugins for a placeholder on the given page using shallow copies of the given context, and returns a string containing the rendered output. """ from cms.plugins.utils import get_plugins context = context_to_copy context.push() request = context['request'] lang = get_language_from_request(request) plugins = [plugin for plugin in get_plugins(request, placeholder)] if not plugins and settings.CMS_LANGUAGE_FALLBACK and lang != get_default_language(): fallbacks = get_fallback_languages(lang) for l in fallbacks: plugins = [plugin for plugin in get_plugins(request, placeholder, l)] if plugins: break page = get_page_from_placeholder_if_exists(placeholder) if page: template = page.template else: template = None # Add extra context as defined in settings, but do not overwrite existing context variables, # since settings are general and database/template are specific # TODO this should actually happen as a plugin context processor, but these currently overwrite # existing context -- maybe change this order? slot = getattr(placeholder, 'slot', None) extra_context = {} if slot: extra_context = get_placeholder_conf("extra_context", slot, template, {}) for key, value in extra_context.items(): if not key in context: context[key] = value c = [] # Prepend frontedit toolbar output if applicable edit = False toolbar = getattr(request, 'toolbar', None) if (getattr(toolbar, 'edit_mode', False) and (not page or page.has_change_permission(request))): edit = True if edit: from cms.middleware.toolbar import toolbar_plugin_processor processors = (toolbar_plugin_processor,) else: processors = None c.extend(render_plugins(plugins, context, placeholder, processors)) content = "".join(c) if edit: content = render_placeholder_toolbar(placeholder, context, content, name_fallback) context.pop() return content
def get_absolute_url(self, language=None): if not language: language = get_current_language() or get_default_language() slug, language = self.known_translation_getter( 'slug', None, language_code=language) if slug: kwargs = {'slug': slug} else: kwargs = {'pk': self.pk} with override(language): return reverse('aldryn_people:group-detail', kwargs=kwargs)
def process_request(self, request): #return super(MultilingualMiddleware, self).process_request(request) setting = getattr(settings, 'CMS_DEFAULT_LANGUAGE', 'default') if setting is 'default': language = get_default_language() else: language = self.get_language_from_request(request) translation.activate(language) request.LANGUAGE_CODE = language if request.META['PATH_INFO'] == '/' \ and getattr(settings, 'CMS_SEO_ROOT', True): return HttpResponseRedirect('/%s/' % language)
def _get_slug_queryset(self, lookup_model=None): """ Build the queryset we will be using considering options and the object's state. lookup model - model manager to build base queryset. If none self.__class__ would be used. """ language = self.get_current_language() or get_default_language() if lookup_model is None: lookup_model = self.__class__ qs = lookup_model.objects.language(language) if not self.slug_globally_unique: qs = qs.filter(translations__language_code=language) if self.pk: qs = qs.exclude(pk=self.pk) return qs
def _get_slug_queryset(self, lookup_model=None): """ Build the queryset we will be using considering options and the object's state. lookup model - model manager to build base queryset. If none self.__class__ would be used. """ language = self.get_current_language() or get_default_language() if lookup_model is None: lookup_model = self.__class__ qs = lookup_model.objects.language(language) if not self.slug_globally_unique: qs = qs.filter( translations__language_code=language) if self.pk: qs = qs.exclude(pk=self.pk) return qs
def known_translation_getter(self, field, default=None, language_code=None, any_language=False): """ This is meant to act like HVAD/Parler's safe_translation_getter() but respects the fallback preferences as defined in `settings.CMS_LANGUAGES` and returns both the translated field value and the language it represents as a tuple: (value, language). If no suitable language is found, then it returns (default, None) """ # NOTE: We're using the CMS fallbacks here, rather than the Parler # fallbacks, the developer should ensure that their project's Parler # settings match the CMS settings. try: object_languages = self.get_available_languages() assert hasattr(object_languages, '__iter__') except [KeyError, AssertionError]: raise ImproperlyConfigured( "TranslationHelperMixin must be used with a model defining" "get_available_languages() that returns a list of available" "language codes. E.g., django-parler's TranslatableModel.") language_code = (language_code or get_current_language() or get_default_language()) site_id = getattr(settings, 'SITE_ID', None) languages = [language_code] + get_fallback_languages(language_code, site_id=site_id) # Grab the first language that is common to our list of fallbacks and # the list of available languages for this object. if languages and object_languages: language_code = next( (lang for lang in languages if lang in object_languages), None) if language_code: value = self.safe_translation_getter( field, default=default, language_code=language_code) return (value, language_code) # No suitable translation exists return (default, None)
def known_translation_getter(self, field, default=None, language_code=None, any_language=False): """ This is meant to act like HVAD/Parler's safe_translation_getter() but respects the fallback preferences as defined in `settings.CMS_LANGUAGES` and returns both the translated field value and the language it represents as a tuple: (value, language). If no suitable language is found, then it returns (default, None) """ # NOTE: We're using the CMS fallbacks here, rather than the Parler # fallbacks, the developer should ensure that their project's Parler # settings match the CMS settings. try: object_languages = self.get_available_languages() assert hasattr(object_languages, '__iter__') except [KeyError, AssertionError]: raise ImproperlyConfigured( "TranslationHelperMixin must be used with a model defining" "get_available_languages() that returns a list of available" "language codes. E.g., django-parler's TranslatableModel.") language_code = ( language_code or get_current_language() or get_default_language()) site_id = getattr(settings, 'SITE_ID', None) languages = [language_code] + get_fallback_languages( language_code, site_id=site_id) # Grab the first language that is common to our list of fallbacks and # the list of available languages for this object. if languages and object_languages: language_code = next( (lang for lang in languages if lang in object_languages), None) if language_code: value = self.safe_translation_getter(field, default=default, language_code=language_code) return (value, language_code) # No suitable translation exists return (default, None)
def add_wizard_button(self): from cms.wizards.wizard_pool import entry_choices title = _("Create") try: page_pk = self.page.pk except AttributeError: page_pk = '' user = getattr(self.request, "user", None) disabled = user and hasattr(self, "page") and len( list(entry_choices(user, self.page))) == 0 lang = get_language_from_request(self.request, current_page=self.page) or get_default_language() url = '{url}?page={page}&language={lang}&edit'.format( url=reverse("cms_wizard_create"), page=page_pk, lang=lang, ) self.toolbar.add_modal_button(title, url, side=self.toolbar.RIGHT, disabled=disabled, on_close=REFRESH_PAGE)
def get_absolute_url(self, language=None): if not language: language = get_current_language() or get_default_language() return self.page.get_absolute_url(language=language)