def list_pages(self, request, template_name=None, extra_context=None): """List root pages""" if not self.admin_site.has_permission(request): return self.admin_site.login(request) language = get_language_from_request(request) query = request.POST.get('q', '').strip() if query: page_ids = list(set([c.page.pk for c in Content.objects.filter(body__icontains=query)])) pages = Page.objects.filter(pk__in=page_ids) else: pages = Page.objects.root() if settings.PAGE_HIDE_SITES: pages = pages.filter(sites=global_settings.SITE_ID) context = { 'can_publish': request.user.has_perm('pages.can_publish'), 'can_import': settings.PAGE_IMPORT_ENABLED, 'lang': language, # lang is the key used by show_content 'pages': pages, 'opts': self.model._meta, 'q': query } context.update(extra_context or {}) change_list = self.changelist_view(request, context) return change_list
def add_view(self, request, form_url='', extra_context=None): """The ``add`` admin view for the :class:`Page <pages.models.Page>`.""" extra_context = { 'language': get_language_from_request(request), 'page_languages': settings.PAGE_LANGUAGES, } return super(PageAdmin, self).add_view(request, form_url, extra_context)
def has_change_permission(self, request, obj=None): """Return ``True`` if the current user has permission to change the page.""" lang = get_language_from_request(request) return PagePermission(request.user).check('change', page=obj, lang=lang, method=request.method)
def test_get_language_from_request(self): """ Test that get_language_from_request return the default language even if a unaccepted language is used. """ class Req(): LANGUAGE_CODE = 'en-us' GET = {} request = Req() self.assertEqual(get_language_from_request(request), 'en-us') request.LANGUAGE_CODE = 'dont' self.assertEqual(get_language_from_request(request), 'en-us') request.LANGUAGE_CODE = 'fr-ch' self.assertEqual(get_language_from_request(request), 'fr-ch')
def test_get_language_from_request(self): """ Test that get_language_from_request return the default language even if a unaccepted language is used. """ class Req: LANGUAGE_CODE = "en-us" GET = {} request = Req() self.assertEqual(get_language_from_request(request), "en-us") request.LANGUAGE_CODE = "dont" self.assertEqual(get_language_from_request(request), "en-us") request.LANGUAGE_CODE = "fr-ch" self.assertEqual(get_language_from_request(request), "fr-ch")
def test_get_language_from_request(self): """ Test that get_language_from_request return the default language even if a unaccepted language is used. """ class Req(): LANGUAGE_CODE = 'en-us' GET = {} request = Req() self.assertEqual( get_language_from_request(request), 'en-us') request.LANGUAGE_CODE = 'dont' self.assertEqual( get_language_from_request(request), 'en-us') request.LANGUAGE_CODE = 'fr-ch' self.assertEqual( get_language_from_request(request), 'fr-ch')
def list_pages_ajax(request, invalid_move=False): """Render pages table for ajax function.""" language = get_language_from_request(request) pages = Page.objects.root() context = { 'can_publish': request.user.has_perm('pages.can_publish'), 'invalid_move': invalid_move, 'language': language, 'pages': pages, } return render(request, "admin/pages/page/change_list_table.html", context)
def list_pages_ajax(request, invalid_move=False): """Render pages table for ajax function.""" language = get_language_from_request(request) pages = Page.objects.root() context = { 'can_publish': request.user.has_perm('pages.can_publish'), 'invalid_move':invalid_move, 'language': language, 'pages': pages, } return render(request, "admin/pages/page/change_list_table.html", context)
def change_view(self, request, object_id, form_url='', extra_context=None): """The ``change`` admin view for the :class:`Page <pages.models.Page>`.""" language = get_language_from_request(request) extra_context = { 'language': language, 'page_languages': settings.PAGE_LANGUAGES, } try: int(object_id) except ValueError: raise Http404('The "%s" part of the location is invalid.' % str(object_id)) try: obj = self.model.objects.get(pk=object_id) except self.model.DoesNotExist: # Don't raise Http404 just yet, because we haven't checked # permissions yet. We don't want an unauthenticated user to be able # to determine whether a given object exists. obj = None else: template = get_template_from_request(request, obj) extra_context['placeholders'] = get_placeholders(template) extra_context['traduction_languages'] = [ l for l in settings.PAGE_LANGUAGES if Content.objects.get_content(obj, l[0], "title") and l[0] != language ] extra_context['page'] = obj response = super(PageAdmin, self).change_view(request, object_id, form_url=form_url, extra_context=extra_context) if request.method == 'POST' and isinstance(response, HttpResponseRedirect): if '_continue' in request.POST or '_saveasnew' in request.POST or '_addanother' in request.POST: addlanguage = True else: addlanguage = False if addlanguage: from six.moves import urllib splitted = list(urllib.parse.urlparse(response.url)) query = urllib.parse.parse_qs(splitted[4]) query['language'] = language splitted[4] = urllib.parse.urlencode(query) response = HttpResponseRedirect( urllib.parse.urlunparse(splitted)) return response
def list_pages_ajax(request, invalid_move=False): """Render pages table for ajax function.""" language = get_language_from_request(request) pages = Page.objects.root() perms = PagePermission(request.user) context = { 'can_publish': perms.check('publish'), 'invalid_move':invalid_move, 'language': language, 'pages': pages, } return render_to_response("admin/pages/page/change_list_table.html", context, context_instance=RequestContext(request))
def list_pages_ajax(request, invalid_move=False): """Render pages table for ajax function.""" language = get_language_from_request(request) pages = Page.objects.root() perms = PagePermission(request.user) context = { 'can_publish': perms.check('publish'), 'invalid_move': invalid_move, 'language': language, 'pages': pages, } return render_to_response("admin/pages/page/change_list_table.html", context, context_instance=RequestContext(request))
def import_pages_from_json(modeladmin, request, queryset, template_name="admin/pages/page/import_pages.html"): try: j = request.FILES["json"] except KeyError: return render_to_response( template_name, {"nofile": True, "app_label": "pages", "opts": Page._meta}, RequestContext(request) ) errors, pages_created = json_to_pages(j.read(), request.user, get_language_from_request(request)) return render_to_response( template_name, {"errors": errors, "pages_created": pages_created, "app_label": "pages", "opts": Page._meta}, RequestContext(request), )
def choose_language(self, lang, request): """Deal with the multiple corner case of choosing the language.""" # Can be an empty string or None if not lang: lang = get_language_from_request(request) # Raise a 404 if the language is not in not in the list if lang not in [key for (key, value) in settings.PAGE_LANGUAGES]: raise Http404 # We're going to serve CMS pages in language lang; # make django gettext use that language too if lang and translation.check_for_language(lang): translation.activate(lang) return lang
def change_view(self, request, object_id, form_url='', extra_context=None): """The ``change`` admin view for the :class:`Page <pages.models.Page>`.""" language = get_language_from_request(request) extra_context = { 'language': language, 'page_languages': settings.PAGE_LANGUAGES, } try: int(object_id) except ValueError: raise Http404('The "%s" part of the location is invalid.' % str(object_id)) try: obj = self.model.objects.get(pk=object_id) except self.model.DoesNotExist: # Don't raise Http404 just yet, because we haven't checked # permissions yet. We don't want an unauthenticated user to be able # to determine whether a given object exists. obj = None else: template = get_template_from_request(request, obj) extra_context['placeholders'] = get_placeholders(template) extra_context['traduction_languages'] = [l for l in settings.PAGE_LANGUAGES if Content.objects.get_content(obj, l[0], "title") and l[0] != language] extra_context['page'] = obj response = super(PageAdmin, self).change_view(request, object_id, form_url=form_url, extra_context=extra_context) if request.method == 'POST' and isinstance(response, HttpResponseRedirect): if '_continue' in request.POST or '_saveasnew' in request.POST or '_addanother' in request.POST: addlanguage = True else: addlanguage = False if addlanguage: from six.moves import urllib splitted = list(urllib.parse.urlparse(response.url)) query = urllib.parse.parse_qs(splitted[4]) query['language'] = language splitted[4] = urllib.parse.urlencode(query) response = HttpResponseRedirect(urllib.parse.urlunparse(splitted)) return response
def get_form(self, request, obj=None, **kwargs): """Get a :class:`Page <pages.admin.forms.PageForm>` for the :class:`Page <pages.models.Page>` and modify its fields depending on the request.""" template = get_template_from_request(request, obj) #model = create_page_model(get_placeholders(template)) form = make_form(self.model, get_placeholders(template)) # bound the form language = get_language_from_request(request) form.base_fields['language'].initial = language if obj: initial_slug = obj.slug(language=language, fallback=False) initial_title = obj.title(language=language, fallback=False) form.base_fields['slug'].initial = initial_slug form.base_fields['title'].initial = initial_title template = get_template_from_request(request, obj) page_templates = settings.get_page_templates() template_choices = list(page_templates) # is default template is not in the list add it if not [ tpl for tpl in template_choices if tpl[0] == settings.PAGE_DEFAULT_TEMPLATE ]: template_choices.insert( 0, (settings.PAGE_DEFAULT_TEMPLATE, _('Default template'))) form.base_fields['template'].choices = template_choices form.base_fields['template'].initial = force_text(template) for placeholder in get_placeholders(template): ctype = placeholder.ctype if obj: initial = placeholder.get_content(obj, language, lang_fallback=False) else: initial = None form.base_fields[ctype] = placeholder.get_field(obj, language, initial=initial) return form
def get_form(self, request, obj=None, **kwargs): """Get a :class:`Page <pages.admin.forms.PageForm>` for the :class:`Page <pages.models.Page>` and modify its fields depending on the request.""" template = get_template_from_request(request, obj) model = create_page_model(get_placeholders(template)) form = make_form(model) # bound the form language = get_language_from_request(request) form.base_fields['language'].initial = language if obj: initial_slug = obj.slug(language=language, fallback=False) initial_title = obj.title(language=language, fallback=False) form.base_fields['slug'].initial = initial_slug form.base_fields['title'].initial = initial_title form.base_fields['slug'].label = _('Slug') template = get_template_from_request(request, obj) page_templates = settings.get_page_templates() if len(page_templates) > 0: template_choices = list(page_templates) template_choices.insert( 0, (settings.PAGE_DEFAULT_TEMPLATE, _('Default template'))) form.base_fields['template'].choices = template_choices form.base_fields['template'].initial = force_text(template) for placeholder in get_placeholders(template): name = placeholder.name if obj: initial = placeholder.get_content(obj, language, name) else: initial = None form.base_fields[name] = placeholder.get_field(obj, language, initial=initial) return form
def import_pages_from_json(modeladmin, request, queryset, template_name='admin/pages/page/import_pages.html'): try: j = request.FILES['json'] except KeyError: return render(request, template_name, { 'nofile': True, 'app_label': 'pages', 'opts': Page._meta, }, RequestContext(request)) errors, pages_created = json_to_pages(j.read(), request.user, get_language_from_request(request)) return render(request, template_name, { 'errors': errors, 'pages_created': pages_created, 'app_label': 'pages', 'opts': Page._meta, }, RequestContext(request))
def get_form(self, request, obj=None, **kwargs): """Get a :class:`Page <pages.admin.forms.PageForm>` for the :class:`Page <pages.models.Page>` and modify its fields depending on the request.""" template = get_template_from_request(request, obj) model = create_page_model(get_placeholders(template)) form = make_form(model) # bound the form language = get_language_from_request(request) form.base_fields['language'].initial = language if obj: initial_slug = obj.slug(language=language, fallback=False) initial_title = obj.title(language=language, fallback=False) form.base_fields['slug'].initial = initial_slug form.base_fields['title'].initial = initial_title form.base_fields['slug'].label = _('Slug') template = get_template_from_request(request, obj) page_templates = settings.get_page_templates() if len(page_templates) > 0: template_choices = list(page_templates) template_choices.insert(0, (settings.PAGE_DEFAULT_TEMPLATE, _('Default template'))) form.base_fields['template'].choices = template_choices form.base_fields['template'].initial = force_text(template) for placeholder in get_placeholders(template): name = placeholder.name if obj: initial = placeholder.get_content(obj, language, name) else: initial = None form.base_fields[name] = placeholder.get_field(obj, language, initial=initial) return form
def get_form(self, request, obj=None, **kwargs): """Get a :class:`Page <pages.admin.forms.PageForm>` for the :class:`Page <pages.models.Page>` and modify its fields depending on the request.""" template = get_template_from_request(request, obj) #model = create_page_model(get_placeholders(template)) form = make_form(self.model, get_placeholders(template)) # bound the form language = get_language_from_request(request) form.base_fields['language'].initial = language if obj: initial_slug = obj.slug(language=language, fallback=False) initial_title = obj.title(language=language, fallback=False) form.base_fields['slug'].initial = initial_slug form.base_fields['title'].initial = initial_title template = get_template_from_request(request, obj) page_templates = settings.get_page_templates() template_choices = list(page_templates) # is default template is not in the list add it if not [tpl for tpl in template_choices if tpl[0] == settings.PAGE_DEFAULT_TEMPLATE]: template_choices.insert(0, (settings.PAGE_DEFAULT_TEMPLATE, _('Default template'))) form.base_fields['template'].choices = template_choices form.base_fields['template'].initial = force_text(template) for placeholder in get_placeholders(template): ctype = placeholder.ctype if obj: initial = placeholder.get_content(obj, language, lang_fallback=False) else: initial = None form.base_fields[ctype] = placeholder.get_field(obj, language, initial=initial) return form
def import_pages_from_json(modeladmin, request, queryset, template_name='admin/pages/page/import_pages.html'): try: j = request.FILES['json'] except KeyError: return render_to_response(template_name, { 'nofile': True, 'app_label': 'pages', 'opts': Page._meta, }, RequestContext(request)) errors, pages_created = json_to_pages(j.read(), request.user, get_language_from_request(request)) return render_to_response( template_name, { 'errors': errors, 'pages_created': pages_created, 'app_label': 'pages', 'opts': Page._meta, }, RequestContext(request))
def has_delete_permission(self, request, obj=None): """Return ``True`` if the current user has permission on the page.""" lang = get_language_from_request(request) return PagePermission(request.user).check('change', page=obj, lang=lang)
def has_add_permission(self, request): """Return ``True`` if the current user has permission to add a new page.""" lang = get_language_from_request(request) return PagePermission(request.user).check('add', lang=lang)