Пример #1
0
    def list_pages(self, request, template_name=None, extra_context=None):
        """List root pages"""
        if not admin.site.has_permission(request):
            return 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.filter(parent__isnull=True)
        if settings.PAGE_HIDE_SITES:
            pages = pages.filter(sites=settings.SITE_ID)

        perms = PagePermission(request.user)
        context = {
            'can_publish': perms.check('publish'),
            'language': language,
            'name': _("page"),
            'pages': pages,
            'opts': self.model._meta,
            'q': query
        }

        context.update(extra_context or {})
        change_list = self.changelist_view(request, context)

        return change_list
Пример #2
0
    def list_pages(self, request, template_name=None, extra_context=None):
        """List root pages"""
        if not admin.site.has_permission(request):
            return 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()

        context = {
            'language': language,
            'name': _("page"),
            'pages': pages,
            'opts': self.model._meta,
            'q': query
        }

        # sad hack for ajax
        # if template_name:
        #    self.change_list_template = template_name
        context.update(extra_context or {})
        change_list = self.changelist_view(request, context)
        #self.change_list_template = 'admin/pages/page/change_list.html'
        #
        return change_list
Пример #3
0
 def change_view(self, request, object_id, extra_context=None):
     """The ``change`` admin view for the
     :class:`Page <pages.models.Page>`."""
     language = get_language_from_request(request)
     extra_context = {
         'language': language,
         # don't see where it's used
         #'lang': current_lang,
         '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
     return super(PageAdmin, self).change_view(request, object_id,
                                               extra_context)
Пример #4
0
    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."""
        form = super(PageAdmin, self).get_form(request, obj, **kwargs)

        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_unicode(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
Пример #5
0
    def list_pages(self, request, template_name=None, extra_context=None):
        """List root pages"""
        if not admin.site.has_permission(request):
            return 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.filter(parent__isnull=True)
        if settings.PAGE_HIDE_SITES:
            pages = pages.filter(sites=settings.SITE_ID)

        perms = PagePermission(request.user)
        context = {
            "can_publish": perms.check("publish"),
            "language": language,
            "name": _("page"),
            "pages": pages,
            "opts": self.model._meta,
            "q": query,
        }

        context.update(extra_context or {})
        change_list = self.changelist_view(request, context)

        return change_list
Пример #6
0
 def change_view(self, request, object_id, extra_context=None):
     """The ``change`` admin view for the
     :class:`Page <pages.models.Page>`."""
     language = get_language_from_request(request)
     extra_context = {
         'language': language,
         # don't see where it's used
         #'lang': current_lang,
         '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
     return super(PageAdmin, self).change_view(request, object_id,
                                                     extra_context)
Пример #7
0
    def list_pages(self, request, template_name=None, extra_context=None):
        """List root pages"""
        if not admin.site.has_permission(request):
            return admin.site.login(request)
        # HACK: overrides the changelist template and later resets it to None
        if template_name:
            self.change_list_template = template_name
        language = get_language_from_request(request)

        q=request.POST.get('q', '').strip()

        if q:
            page_ids = list(set([c.page.pk for c in Content.objects.filter(body__icontains=q)]))
            pages = Page.objects.filter(pk__in=page_ids)
        else:
            pages = Page.objects.root()

        context = {
            'language': language,
            'name': _("page"),
            'pages': pages,
            'opts': self.model._meta,
            'q': q
        }

        context.update(extra_context or {})
        change_list = self.changelist_view(request, context)

        self.change_list_template = None
        return change_list
Пример #8
0
    def list_pages(self, request, template_name=None, extra_context=None):
        """List root pages"""
        if not admin.site.has_permission(request):
            return 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=settings.SITE_ID)

        perms = PagePermission(request.user)
        context = {
            'can_publish': perms.check('publish'),
            'language': language,
            'name': _("page"),
            'pages': pages,
            'opts': self.model._meta,
            'q': query
        }

        context.update(extra_context or {})
        change_list = self.changelist_view(request, context)

        return change_list
Пример #9
0
    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."""
        form = super(PageAdmin, self).get_form(request, obj, **kwargs)

        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_unicode(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
Пример #10
0
 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)
Пример #11
0
    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')
Пример #12
0
 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)
Пример #13
0
    def get_form(self, request, obj=None, **kwargs):
        """Get a :class:`Category <pages.admin.forms.CategoryForm>` for the
        :class:`Category <pages.models.Category>` and modify its fields depending on
        the request."""
        form = super(CategoryAdmin, self).get_form(request, obj, **kwargs)

        language = get_language_from_request(request)
        form.base_fields['language'].initial = language

        return form
Пример #14
0
def list_pages_ajax(request, invalid_move=False):
    """Render pages table for ajax function."""
    language = get_language_from_request(request)
    pages = Page.objects.filter(parent__isnull=True)
    context = {
        'invalid_move':invalid_move,
        'language': language,
        'pages': pages,
    }
    return "admin/pages/page/change_list_table.html", context
Пример #15
0
 def add_view(self, request, form_url='', extra_context=None):
     """The 'add' admin view for the Page model."""
     extra_context = {
         'language': get_language_from_request(request),
         'page_languages': settings.PAGE_LANGUAGES,
     }
     template = get_template_from_request(request)
     #extra_context['placeholders'] = get_placeholders(template)
     return super(PageAdmin, self).add_view(request, form_url,
                                                         extra_context)
Пример #16
0
def list_pages_ajax(request, invalid_move=False):
    """Render pages table for ajax function."""
    language = get_language_from_request(request)
    pages = Page.objects.filter(parent__isnull=True)
    context = {
        'invalid_move': invalid_move,
        'language': language,
        'pages': pages,
    }
    return "admin/pages/page/change_list_table.html", context
Пример #17
0
    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')
Пример #18
0
 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,
     }
     template = get_template_from_request(request)
     #extra_context['placeholders'] = get_placeholders(template)
     return super(PageAdmin, self).add_view(request, form_url,
                                            extra_context)
Пример #19
0
def import_pages_from_json(request,
        template_name='admin/pages/page/import_pages.html'):
    try:
        d = simplejson.load(request.FILES['json'])
    except KeyError:
        return redirect('admin:page-index')

    try:
        errors = validate_pages_json_data(d, get_language_from_request(request))
    except KeyError, e:
        errors = [_('JSON file is invalid: %s') % (e.args[0],)]
Пример #20
0
def import_pages_from_json(request,
                           template_name='admin/pages/page/import_pages.html'):
    try:
        d = simplejson.load(request.FILES['json'])
    except KeyError:
        return redirect('admin:page-index')

    try:
        errors = validate_pages_json_data(d,
                                          get_language_from_request(request))
    except KeyError, e:
        errors = [_('JSON file is invalid: %s') % (e.args[0], )]
Пример #21
0
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 "admin/pages/page/change_list_table.html", context
Пример #22
0
def import_pages_from_json(request,
        template_name='admin/pages/page/import_pages.html'):
    try:
        j = request.FILES['json']
    except KeyError:
        return redirect('admin:page-index')

    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))
Пример #23
0
 def list_pages(self, request, template_name=None, extra_context=None):
     """List root pages"""
     # HACK: overrides the changelist template and later resets it to None
     if template_name:
         self.change_list_template = template_name
     lang = get_language_from_request(request)
     context = {
         'lang': lang,
         'name': _("page"),
         'pages': Page.objects.root().order_by("tree_id"),
         'opts': self.model._meta
     }
     context.update(extra_context or {})
     change_list = self.changelist_view(request, context)
     self.change_list_template = None
     return change_list
Пример #24
0
    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
Пример #25
0
    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
Пример #26
0
    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:
                import urllib
                import urlparse
                splitted = list(urlparse.urlparse(response.url))
                query = urlparse.parse_qs(splitted[4])
                query['language'] = language
                splitted[4] = urllib.urlencode(query)
                response = HttpResponseRedirect(urlparse.urlunparse(splitted))
        return response
Пример #27
0
    def get_form(self, request, obj=None, **kwargs):
        form = super(PageAdminWithDefaultContent, self).get_form(request, obj, **kwargs)

        language = get_language_from_request(request)

        if global_settings.LANGUAGE_CODE == language:
            # this is the "official" language
            return form

        if Content.objects.filter(page=obj, language=language).count():
            return form

        # this is a new page, try to find some default content
        template = get_template_from_request(request, obj)
        for placeholder in get_placeholders(template):
            name = placeholder.name
            form.base_fields[name] = placeholder.get_field(
                obj, language, initial=Content.objects.get_content(obj, global_settings.LANGUAGE_CODE, name)
            )
        return form
Пример #28
0
    def get_form(self, request, obj=None, **kwargs):
        """Get PageForm for the Page model and modify its fields depending on
        the request."""
        form = super(PageAdmin, self).get_form(request, obj, **kwargs)

        language = get_language_from_request(request, obj)
        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)
        if settings.PAGE_TEMPLATES:
            template_choices = list(settings.PAGE_TEMPLATES)
            template_choices.insert(0, (settings.DEFAULT_PAGE_TEMPLATE,
                    _('Default template')))
            form.base_fields['template'].choices = template_choices
            form.base_fields['template'].initial = force_unicode(template)

        for placeholder in get_placeholders(template):
            widget = self.get_widget(placeholder.widget)()
            if placeholder.parsed:
                help_text = _('Note: This field is evaluated as template code.')
            else:
                help_text = ""
            name = placeholder.name
            if obj:
                initial = Content.objects.get_content(obj, language, name)
            else:
                initial = None
            if name not in self.mandatory_placeholders:
                form.base_fields[placeholder.name] = CharField(widget=widget,
                    initial=initial, help_text=help_text, required=False)
            else:
                form.base_fields[name].initial = initial
                form.base_fields[name].help_text = help_text

        return form
Пример #29
0
    def get_form(self, request, obj=None, **kwargs):
        form = super(PageAdminWithDefaultContent, self
            ).get_form(request, obj, **kwargs)

        language = get_language_from_request(request)

        if global_settings.LANGUAGE_CODE == language:
            # this is the "official" language
            return form

        if Content.objects.filter(page=obj, language=language).count():
            return form

        # this is a new page, try to find some default content
        template = get_template_from_request(request, obj)
        for placeholder in get_placeholders(template):
            name = placeholder.name
            form.base_fields[name] = placeholder.get_field(obj, language,
                initial=Content.objects.get_content(obj,
                    global_settings.LANGUAGE_CODE, name))
        return form
Пример #30
0
 def change_view(self, request, object_id, extra_context=None):
     """The 'change' admin view for the Page model."""
     extra_context = {
         'language': get_language_from_request(request),
         'page_languages': settings.PAGE_LANGUAGES,
     }
     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")]
     extra_context['page'] = obj
     return super(PageAdmin, self).change_view(request, object_id,
                                                     extra_context)
Пример #31
0
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 = {"invalid_move": invalid_move, "language": language, "pages": pages}
    return "admin/pages/page/change_list_table.html", context
Пример #32
0
 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)
Пример #33
0
 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)
Пример #34
0
 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)
Пример #35
0
def details(request, path=None, lang=None):
    """This view get the root pages for navigation
    and the current page to display if there is any.

    All is rendered with the current page's template.

    This view use the auto_render decorator. It means
    that you can use the only_context extra parameter to get
    only the local variables of this view without rendering
    the template.

    >>> from pages.views import details
    >>> context = details(request, only_context=True)

    This can be usefull if you want to write your own
    view. You can reuse the following code without having to
    copy and paste it."""
    
    pages = Page.objects.navigation().order_by("tree_id")
    current_page = False

    if lang is None:
        lang = get_language_from_request(request, current_page)

    if lang not in [key for (key, value) in settings.PAGE_LANGUAGES]:
        raise Http404

    if path:
        current_page = Page.objects.from_path(path, lang)
    elif pages:
        current_page = pages[0]

    # if no pages has been found, we will try to find an Alias
    if not current_page:
        alias = PageAlias.objects.from_path(request, path, lang)
        if not alias:
            raise Http404
        url  = alias.page.get_absolute_url(lang)
        return HttpResponsePermanentRedirect(url)

    if not (request.user.is_authenticated() and request.user.is_staff) and \
        current_page.calculated_status in (Page.DRAFT, Page.EXPIRED):
        raise Http404
    
    if current_page.redirect_to:
        return HttpResponsePermanentRedirect(
            current_page.redirect_to.get_absolute_url(lang))
    
    template_name = current_page.get_template()
    
    if request.is_ajax():
        new_template_name = "body_%s" % template_name
        return new_template_name, locals()

    return template_name, {
        'path': path,
        'pages': pages,
        'current_page': current_page,
        'lang': lang,
        'request': request,
    }
Пример #36
0
def details(request, path=None, lang=None, delegation=True, **kwargs):
    """This view get the root pages for navigation
    and the current page to display if there is any.

    All is rendered with the current page's template.

    This view use the auto_render decorator. It means
    that you can use the only_context extra parameter to get
    only the local variables of this view without rendering
    the template.

    >>> from pages.views import details
    >>> context = details(request, only_context=True)

    This can be usefull if you want to write your own
    view. You can reuse the following code without having to
    copy and paste it."""
    
    pages_navigation = Page.objects.navigation().order_by("tree_id")
    current_page = False
    template_name = settings.PAGE_DEFAULT_TEMPLATE

    if path is None:
        slug, path, lang = get_slug_and_relative_path(request.path, lang)

    # Can be an empty string or None
    if not lang:
        lang = get_language_from_request(request)

    context = {
        'path': path,
        'pages_navigation': pages_navigation,
        'lang': lang,
    }

    if lang not in [key for (key, value) in settings.PAGE_LANGUAGES]:
        raise Http404

    is_user_staff = request.user.is_authenticated() and request.user.is_staff
    if path:
        current_page = Page.objects.from_path(path, lang,
            exclude_drafts=(not is_user_staff))
    elif pages_navigation:
        current_page = Page.objects.root()[0]

    # if no pages has been found, we will try to find it via an Alias
    if not current_page:
        alias = PageAlias.objects.from_path(request, path, lang)
        if alias:
            url = alias.page.get_url_path(lang)
            return HttpResponsePermanentRedirect(url)
        raise Http404

    if ((not is_user_staff) and
            current_page.calculated_status in (Page.DRAFT, Page.EXPIRED)):
        raise Http404

    if current_page.redirect_to_url:
        return HttpResponsePermanentRedirect(current_page.redirect_to_url)
    
    if current_page.redirect_to:
        return HttpResponsePermanentRedirect(
            current_page.redirect_to.get_url_path(lang))
    
    template_name = current_page.get_template()
    
    if request.is_ajax():
        template_name = "body_%s" % template_name

    if current_page:
        context['current_page'] = current_page

    if settings.PAGE_EXTRA_CONTEXT:
        context.update(settings.PAGE_EXTRA_CONTEXT())

    if delegation and current_page.delegate_to:
        urlconf = get_urlconf(current_page.delegate_to)
        result = resolve('/', urlconf)
        if len(result):
            view, args, kwargs = result
            kwargs['current_page'] = current_page
            kwargs['path'] = path
            kwargs['lang'] = lang
            kwargs['pages_navigation'] = pages_navigation
            return view(
                request,
                *args,
                **kwargs
            )

    return template_name, context
Пример #37
0
 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)
Пример #38
0
 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}
     template = get_template_from_request(request)
     # extra_context['placeholders'] = get_placeholders(template)
     return super(PageAdmin, self).add_view(request, form_url, extra_context)