def test_multiple_matches_returns_max_3_top_matches(self):
        home_page = Page.objects.get(slug='home')
        match_1 = Page(title='Bridget Masinga',
                       slug='bridgetmasinga',
                       live=True,
                       first_published_at=datetime.now())
        match_2 = Page(title='Bridget Masinga1',
                       slug='bridgetmasinga1',
                       live=True,
                       first_published_at=datetime.now())
        match_3 = Page(title='Bridget Masinga2',
                       slug='bridgetmasinga2',
                       live=True,
                       first_published_at=datetime.now())
        match_4 = Page(title='Bridget Masinga3',
                       slug='bridgetmasinga3',
                       live=True,
                       first_published_at=datetime.now())
        home_page.add_child(instance=match_1)
        home_page.add_child(instance=match_2)
        home_page.add_child(instance=match_3)
        home_page.add_child(instance=match_4)

        result = suggest_page_from_misspelled_slug('/bridget', home_page)

        assert len(result) == 3
Ejemplo n.º 2
0
 def test_page(self):
     page = Page(title='testpage',
                 slug='test',
                 path='000100019999',
                 depth=3)
     page.save()
     return page
Ejemplo n.º 3
0
    def handle(self, *args, **options):
        # Get blogpage content type
        blogpage_content_type, created = ContentType.objects.get_or_create(
            model='blogpage',
            app_label='puput',
            defaults={'name': 'page'} if DJANGO_VERSION < (1, 8) else {}
        )

        # Get root page
        rootpage = Page.objects.first()

        # Set site root page as root site page
        site = Site.objects.first()
        site.root_page = rootpage
        site.save()

        # Create example blog page
        blogpage = Page(
            title="Blog",
            content_type=blogpage_content_type,
            slug='blog',
        )

        # Add blog page as a child for homepage
        rootpage.add_child(instance=blogpage)
        revision = blogpage.save_revision()
        revision.publish()
 def test_page(self):
     page = Page(
         title='testpage',
         slug='test',
         path='000100019999',
         depth=3
     )
     page.save()
     return page
Ejemplo n.º 5
0
def test_page_multiple_roots():
    # Make sure the default root pages are removed created by wagtail
    # migrations
    Page.get_root_nodes().delete()
    assert Page.get_root_nodes().count() == 0

    wagtail_factories.PageFactory(parent=None)
    wagtail_factories.PageFactory(parent=None)
    wagtail_factories.PageFactory(parent=None)
    assert Page.get_root_nodes().count() == 3
Ejemplo n.º 6
0
    def handle_noargs(self, **options):
        problems_found = False

        for page in Page.objects.all():
            try:
                page.specific
            except ObjectDoesNotExist:
                self.stdout.write(
                    "Page %d (%s) is missing a subclass record; deleting." %
                    (page.id, page.title))
                problems_found = True
                page.delete()

        (_, _, _, bad_depth, bad_numchild) = Page.find_problems()
        if bad_depth:
            self.stdout.write("Incorrect depth value found for pages: %r" %
                              bad_depth)
        if bad_numchild:
            self.stdout.write("Incorrect numchild value found for pages: %r" %
                              bad_numchild)

        if bad_depth or bad_numchild:
            Page.fix_tree(destructive=False)
            problems_found = True

        remaining_problems = Page.find_problems()
        if any(remaining_problems):
            self.stdout.write("Remaining problems (cannot fix automatically):")
            (bad_alpha, bad_path, orphans, bad_depth,
             bad_numchild) = remaining_problems
            if bad_alpha:
                self.stdout.write(
                    "Invalid characters found in path for pages: %r" %
                    bad_alpha)
            if bad_path:
                self.stdout.write("Invalid path length found for pages: %r" %
                                  bad_path)
            if orphans:
                self.stdout.write("Orphaned pages found: %r" % orphans)
            if bad_depth:
                self.stdout.write("Incorrect depth value found for pages: %r" %
                                  bad_depth)
            if bad_numchild:
                self.stdout.write(
                    "Incorrect numchild value found for pages: %r" %
                    bad_numchild)

        elif problems_found:
            self.stdout.write("All problems fixed.")
        else:
            self.stdout.write("No problems found.")
    def test_search_does_not_return_copied_pages(self):
        home_page = Page.objects.get(slug='home')
        bieber_article = Page(
            title='Justin Bieber',
            slug='justin-bieber'
        )
        home_page.add_child(instance=bieber_article)
        bieber_article_copy = bieber_article.copy(
            update_attrs={'slug': 'justin-bieber-copy'}
        )

        result = pg_full_text_search('Justin Bieber', home_page)

        assert list(result) == [bieber_article]
Ejemplo n.º 8
0
    def test_construct_queryset_hook(self):
        page = SimplePage(title="Test shown", content="hello")
        Page.get_first_root_node().add_child(instance=page)

        page_not_shown = SimplePage(title="Test not shown", content="hello")
        Page.get_first_root_node().add_child(instance=page_not_shown)

        def filter_pages(pages, request):
            return pages.filter(id=page.id)

        with self.register_hook('construct_page_chooser_queryset', filter_pages):
            response = self.get()
        self.assertEqual(len(response.context['pages']), 1)
        self.assertEqual(response.context['pages'][0].specific, page)
Ejemplo n.º 9
0
    def setUp(self):
        root = Page.objects.get(pk=1)
        root_a = Page(
            title='Home A', slug='home-a')
        root.add_child(instance=root_a)

        root_b = Page(
            title='Home B', slug='home-b')
        root.add_child(instance=root_b)

        self.index_a = NewsIndex(title='News A', slug='news-a')
        root_a.add_child(instance=self.index_a)

        self.index_b = NewsIndex(title='News B', slug='news-b')
        root_b.add_child(instance=self.index_b)

        self.site_a = Site.objects.create(
            hostname='site-a.com',
            root_page=root_a)

        self.site_b = Site.objects.create(
            hostname='site-b.org',
            root_page=root_b)

        self.item_a = NewsItem.objects.create(
            newsindex=self.index_a, title='Post A', date=dt(2015, 8, 1))
        self.item_b = NewsItem.objects.create(
            newsindex=self.index_b, title='Post B', date=dt(2015, 8, 2))
Ejemplo n.º 10
0
    def test_get_root_page__more_than_one(self):
        """
        If there are multiple root pages in the database, `get_root_page`
        should raise a MultipleObjectsReturned exception
        """
        # Create a new root page
        Page.add_root(instance=Page(title="Route 2"))

        with self.assertRaises(Site.MultipleObjectsReturned) as cm:
            get_root_page()

        self.assertEqual(
            cm.exception.args,
            ('Foliage can\'t auto-determine the root page. '
             'More than one Page exists with depth 1 in the database!', ))
Ejemplo n.º 11
0
    def search_view(self, request):
        # Search
        query_string = request.GET.get('q', None)
        if query_string is not None:
            # Get list of live subpages of the homepage
            # for current language.
            pages = Page.objects.descendant_of(self).live()

            # TODO: Remove pages from PageQuerySet that don't stem
            # from current language's home page.

            # Search them

            # Waiting on wagtail to push PageQuerySet.search() to
            # the public repo.
            pages = pages.search(query_string)
        else:
            pages = Page.objects.none()

        # Pagination
        # TODO

        # Update context
        context = Page.get_context(self, request)
        context['query_string'] = query_string
        context['pages'] = pages
        return TemplateResponse(request, self.search_template, context)
Ejemplo n.º 12
0
    def test_build_page_tree__database(self):
        """
        `build_page_tree` should save all page nodes to the database
        """

        home_page = HomePage(title="Home Page")
        inside_page_1 = InsidePage(title="Inside Page 1")
        inside_page_2 = InsidePage(title="Inside Page 2")
        inside_page_2_1 = InsidePage(title="Inside Page 2, 1")

        page_tree = [(home_page, [
            inside_page_1,
            (inside_page_2, [inside_page_2_1]),
        ])]
        build_page_tree(page_tree)
        data = Page.dump_bulk(HomePage.objects.get())

        self.assertEqual(data[0]['data']['title'], "Home Page")
        # Home page should have exactly two children with the correct titles
        self.assertEqual(len(data[0]['children']), 2)
        self.assertEqual(data[0]['children'][0]['data']['title'],
                         "Inside Page 1")
        self.assertEqual(data[0]['children'][1]['data']['title'],
                         "Inside Page 2")
        # Child 1 should have zero children
        self.assertNotIn('children', data[0]['children'][0])
        # Child 2 should have one child with the proper title
        self.assertEqual(len(data[0]['children'][1]['children']), 1)
        self.assertEqual(
            data[0]['children'][1]['children'][0]['data']['title'],
            "Inside Page 2, 1")
Ejemplo n.º 13
0
    def _create(cls, *args, **kwargs):
        try:
            root = Page.objects.get(depth=0)
        except Page.DoesNotExist:
            root = Page.add_root(title='root')

        return root.add_child(title=kwargs['title'])
Ejemplo n.º 14
0
def move_choose_destination(request, page_to_move_id, viewed_page_id=None):
    page_to_move = get_object_or_404(Page, id=page_to_move_id)
    page_perms = page_to_move.permissions_for_user(request.user)
    if not page_perms.can_move():
        raise PermissionDenied

    if viewed_page_id:
        viewed_page = get_object_or_404(Page, id=viewed_page_id)
    else:
        viewed_page = Page.get_first_root_node()

    viewed_page.can_choose = page_perms.can_move_to(viewed_page)

    child_pages = []
    for target in viewed_page.get_children():
        # can't move the page into itself or its descendants
        target.can_choose = page_perms.can_move_to(target)

        target.can_descend = not(target == page_to_move or target.is_child_of(page_to_move)) and target.get_children_count()

        child_pages.append(target)

    return render(request, 'wagtailadmin/pages/move_choose_destination.html', {
        'page_to_move': page_to_move,
        'viewed_page': viewed_page,
        'child_pages': child_pages,
    })
Ejemplo n.º 15
0
def index(request, parent_page_id=None):
    if parent_page_id:
        parent_page = get_object_or_404(Page, id=parent_page_id)
    else:
        parent_page = Page.get_first_root_node()

    pages = parent_page.get_children().prefetch_related('content_type')

    # Get page ordering
    if 'ordering' in request.GET:
        ordering = request.GET['ordering']

        if ordering in [
                'title', '-title', 'content_type', '-content_type', 'live',
                '-live'
        ]:
            pages = pages.order_by(ordering)
    else:
        ordering = 'title'

    return render(request, 'wagtailadmin/pages/index.html', {
        'parent_page': parent_page,
        'ordering': ordering,
        'pages': pages,
    })
Ejemplo n.º 16
0
def index(request, parent_page_id=None):
    if parent_page_id:
        parent_page = get_object_or_404(Page, id=parent_page_id)
    else:
        parent_page = Page.get_first_root_node()

    pages = parent_page.get_children().prefetch_related('content_type')

    # Get page ordering
    ordering = request.GET.get('ordering', '-latest_revision_created_at')
    if ordering not in ['title', '-title', 'content_type', '-content_type', 'live', '-live', 'latest_revision_created_at', '-latest_revision_created_at', 'ord']:
        ordering = '-latest_revision_created_at'

    # Pagination
    if ordering != 'ord':
        ordering_no_minus = ordering
        if ordering_no_minus.startswith('-'):
            ordering_no_minus = ordering[1:]
        pages = pages.order_by(ordering).annotate(null_position=Count(ordering_no_minus)).order_by('-null_position', ordering)

        p = request.GET.get('p', 1)
        paginator = Paginator(pages, 50)
        try:
            pages = paginator.page(p)
        except PageNotAnInteger:
            pages = paginator.page(1)
        except EmptyPage:
            pages = paginator.page(paginator.num_pages)

    return render(request, 'wagtailadmin/pages/index.html', {
        'parent_page': parent_page,
        'ordering': ordering,
        'pagination_query_params': "ordering=%s" % ordering,
        'pages': pages,
    })
Ejemplo n.º 17
0
def move_choose_destination(request, page_to_move_id, viewed_page_id=None):
    page_to_move = get_object_or_404(Page, id=page_to_move_id)
    page_perms = page_to_move.permissions_for_user(request.user)
    if not page_perms.can_move():
        raise PermissionDenied

    if viewed_page_id:
        viewed_page = get_object_or_404(Page, id=viewed_page_id)
    else:
        viewed_page = Page.get_first_root_node()

    viewed_page.can_choose = page_perms.can_move_to(viewed_page)

    child_pages = []
    for target in viewed_page.get_children():
        # can't move the page into itself or its descendants
        target.can_choose = page_perms.can_move_to(target)

        target.can_descend = not (target == page_to_move or target.is_child_of(
            page_to_move)) and target.get_children_count()

        child_pages.append(target)

    return render(
        request, 'wagtailadmin/pages/move_choose_destination.html', {
            'page_to_move': page_to_move,
            'viewed_page': viewed_page,
            'child_pages': child_pages,
        })
Ejemplo n.º 18
0
 def setUp(self):
     home_page = CaosHomePage(title='TestHomePage')
     root_page = Page.get_root_nodes()[0]
     root_page.add_child(instance=home_page)
     sites = Site.objects.get(id=1)
     sites.root_page = home_page
     sites.save()
Ejemplo n.º 19
0
def index(request, parent_page_id=None):
    if parent_page_id:
        parent_page = get_object_or_404(Page, id=parent_page_id)
    else:
        parent_page = Page.get_first_root_node()

    pages = parent_page.get_children().prefetch_related('content_type')

    # Get page ordering
    ordering = request.GET.get('ordering', '-latest_revision_created_at')
    if ordering not in ['title', '-title', 'content_type', '-content_type', 'live', '-live', 'latest_revision_created_at', '-latest_revision_created_at', 'ord']:
        ordering = '-latest_revision_created_at'

    # Pagination
    if ordering != 'ord':
        ordering_no_minus = ordering
        if ordering_no_minus.startswith('-'):
            ordering_no_minus = ordering[1:]
        pages = pages.order_by(ordering).annotate(null_position=Count(ordering_no_minus)).order_by('-null_position', ordering)

        p = request.GET.get('p', 1)
        paginator = Paginator(pages, 50)
        try:
            pages = paginator.page(p)
        except PageNotAnInteger:
            pages = paginator.page(1)
        except EmptyPage:
            pages = paginator.page(paginator.num_pages)

    return render(request, 'wagtailadmin/pages/index.html', {
        'parent_page': parent_page,
        'ordering': ordering,
        'pages': pages,
    })
Ejemplo n.º 20
0
def index(request, parent_page_id=None):
    if parent_page_id:
        parent_page = get_object_or_404(Page, id=parent_page_id)
    else:
        parent_page = Page.get_first_root_node()

    pages = parent_page.get_children().prefetch_related('content_type')

    # Get page ordering
    ordering = request.GET.get('ordering', '-latest_revision_created_at')
    if ordering not in ['title', '-title', 'content_type', '-content_type', 'live', '-live', 'latest_revision_created_at', '-latest_revision_created_at', 'ord']:
        ordering = '-latest_revision_created_at'

    # Pagination
    # Don't paginate if sorting by page order - all pages must be shown to
    # allow drag-and-drop reordering
    do_paginate = ordering != 'ord'
    if do_paginate:
        ordering_no_minus = ordering.lstrip('-')
        pages = pages.order_by(ordering).annotate(null_position=Count(ordering_no_minus)).order_by('-null_position', ordering)
        paginator, pages = paginate(request, pages, per_page=50)

    return render(request, 'wagtailadmin/pages/index.html', {
        'parent_page': parent_page,
        'ordering': ordering,
        'pagination_query_params': "ordering=%s" % ordering,
        'pages': pages,
        'do_paginate': do_paginate,
    })
Ejemplo n.º 21
0
 def setUp(self):
     home_page = CaosHomePage(title='TestHomePage')
     root_page = Page.get_root_nodes()[0]
     root_page.add_child(instance=home_page)
     sites = Site.objects.get(id=1)
     sites.root_page = home_page
     sites.save()
Ejemplo n.º 22
0
def preview_on_create(request, content_type_app_name, content_type_model_name, parent_page_id):
    # Receive the form submission that would typically be posted to the 'create' view. If submission is valid,
    # return the rendered page; if not, re-render the edit form
    try:
        content_type = ContentType.objects.get_by_natural_key(content_type_app_name, content_type_model_name)
    except ContentType.DoesNotExist:
        raise Http404

    page_class = content_type.model_class()
    page = page_class()
    edit_handler_class = page_class.get_edit_handler()
    form_class = edit_handler_class.get_form_class(page_class)
    parent_page = get_object_or_404(Page, id=parent_page_id).specific

    form = form_class(request.POST, request.FILES, instance=page, parent_page=parent_page)

    if form.is_valid():
        form.save(commit=False)

        # We need to populate treebeard's path / depth fields in order to pass validation.
        # We can't make these 100% consistent with the rest of the tree without making actual
        # database changes (such as incrementing the parent's numchild field), but by
        # calling treebeard's internal _get_path method, we can set a 'realistic' value that
        # will hopefully enable tree traversal operations to at least partially work.
        page.depth = parent_page.depth + 1

        if parent_page.is_leaf():
            # set the path as the first child of parent_page
            page.path = page._get_path(parent_page.path, page.depth, 1)
        else:
            # add the new page after the last child of parent_page
            page.path = parent_page.get_last_child()._inc_path()

        # ensure that our unsaved page instance has a suitable url set
        page.set_url_path(parent_page)

        page.full_clean()

        # Set treebeard attributes
        page.depth = parent_page.depth + 1
        page.path = Page._get_children_path_interval(parent_page.path)[1]

        preview_mode = request.GET.get('mode', page.default_preview_mode)
        response = page.serve_preview(page.dummy_request(request), preview_mode)
        response['X-Wagtail-Preview'] = 'ok'
        return response

    else:
        edit_handler = edit_handler_class(instance=page, form=form)

        response = render(request, 'wagtailadmin/pages/create.html', {
            'content_type': content_type,
            'page_class': page_class,
            'parent_page': parent_page,
            'edit_handler': edit_handler,
            'preview_modes': page.preview_modes,
            'form': form,
        })
        response['X-Wagtail-Preview'] = 'error'
        return response
Ejemplo n.º 23
0
def index(request, parent_page_id=None):
    if parent_page_id:
        parent_page = get_object_or_404(Page, id=parent_page_id)
    else:
        parent_page = Page.get_first_root_node()

    pages = parent_page.get_children().prefetch_related('content_type')

    # Get page ordering
    ordering = request.GET.get('ordering', 'title')
    if ordering not in ['title', '-title', 'content_type', '-content_type', 'live', '-live', 'ord']:
        ordering = 'title'

    # Pagination
    if ordering != 'ord':
        pages = pages.order_by(ordering)

        p = request.GET.get('p', 1)
        paginator = Paginator(pages, 50)
        try:
            pages = paginator.page(p)
        except PageNotAnInteger:
            pages = paginator.page(1)
        except EmptyPage:
            pages = paginator.page(paginator.num_pages)

    return render(request, 'wagtailadmin/pages/index.html', {
        'parent_page': parent_page,
        'ordering': ordering,
        'pages': pages,
    })
Ejemplo n.º 24
0
    def clear(self, quiet=False):
        """
        Clear all the RevolvCustomPages and RevolvLinkPages and reset the site
        root page. We need to reset the site root page because of how django-treebeard
        works. In order to keep a tree of related models, the parent Pages store
        meta information about their children, including paths.

        This means that we can't actually just delete all the Page models that
        we created in seed(): we instead have to do that AND delete the root page
        and reset it.

        References:
            wagtail Site model: https://github.com/torchbox/wagtail/blob/e937d7a1a32052966b6dfa9768168ea990f7916a/wagtail/wagtailcore/models.py#L52
            treebeard add_root() docs: https://tabo.pe/projects/django-treebeard/docs/1.61/api.html#treebeard.models.Node.add_root
        """
        try:
            only_site = Site.objects.all()[0]
            only_site.root_page.delete()
            new_root_page = Page.add_root(title="RE-volv Main Site Root")
            only_site.root_page = new_root_page
            only_site.save()
        except ObjectDoesNotExist as e:
            if not quiet:
                print "[Seed:Warning] Error in %s when trying to clear: %s" % (
                    self.__class__.__name__, str(e))
Ejemplo n.º 25
0
def index(request, parent_page_id=None):
    if parent_page_id:
        parent_page = get_object_or_404(Page, id=parent_page_id)
    else:
        parent_page = Page.get_first_root_node()

    pages = parent_page.get_children().prefetch_related("content_type")

    # Get page ordering
    ordering = request.GET.get("ordering", "title")
    if ordering not in ["title", "-title", "content_type", "-content_type", "live", "-live", "ord"]:
        ordering = "title"

    # Pagination
    if ordering != "ord":
        pages = pages.order_by(ordering)

        p = request.GET.get("p", 1)
        paginator = Paginator(pages, 50)
        try:
            pages = paginator.page(p)
        except PageNotAnInteger:
            pages = paginator.page(1)
        except EmptyPage:
            pages = paginator.page(paginator.num_pages)

    return render(
        request, "wagtailadmin/pages/index.html", {"parent_page": parent_page, "ordering": ordering, "pages": pages}
    )
Ejemplo n.º 26
0
    def clean(self):

        cleaned_data = super(WagtailAdminPageForm, self).clean()
        if 'slug' in self.cleaned_data:
            if not Page._slug_is_available(cleaned_data['slug'],
                                           self.parent_page, self.instance):
                self.add_error(
                    'slug',
                    forms.ValidationError(_("This slug is already in use")))

        # Check scheduled publishing fields
        go_live_at = cleaned_data.get('go_live_at')
        expire_at = cleaned_data.get('expire_at')

        # Go live must be before expire
        if go_live_at and expire_at:
            if go_live_at > expire_at:
                msg = _('Go live date/time must be before expiry date/time')
                self.add_error('go_live_at', forms.ValidationError(msg))
                self.add_error('expire_at', forms.ValidationError(msg))

        # Expire at must be in the future
        if expire_at and expire_at < timezone.now():
            self.add_error(
                'expire_at',
                forms.ValidationError(
                    _('Expiry date/time must be in the future')))

        # Don't allow an existing first_published_at to be unset by clearing the field
        if 'first_published_at' in cleaned_data and not cleaned_data[
                'first_published_at']:
            del cleaned_data['first_published_at']

        return cleaned_data
Ejemplo n.º 27
0
    def clean(self):

        cleaned_data = super(WagtailAdminPageForm, self).clean()
        if 'slug' in self.cleaned_data:
            if not Page._slug_is_available(
                cleaned_data['slug'], self.parent_page, self.instance
            ):
                self.add_error('slug', forms.ValidationError(_("This slug is already in use")))

        # Check scheduled publishing fields
        go_live_at = cleaned_data.get('go_live_at')
        expire_at = cleaned_data.get('expire_at')

        # Go live must be before expire
        if go_live_at and expire_at:
            if go_live_at > expire_at:
                msg = _('Go live date/time must be before expiry date/time')
                self.add_error('go_live_at', forms.ValidationError(msg))
                self.add_error('expire_at', forms.ValidationError(msg))

        # Expire at must be in the future
        if expire_at and expire_at < timezone.now():
            self.add_error('expire_at', forms.ValidationError(_('Expiry date/time must be in the future')))

        return cleaned_data
Ejemplo n.º 28
0
 def entries_by_author(self, request, author, *args, **kwargs):
     self.search_type = _('author')
     self.search_term = author
     field_name = 'owner__%s' % getattr(settings, 'PUPUT_USERNAME_FIELD',
                                        'username')
     self.entries = self.get_entries().filter(**{field_name: author})
     return Page.serve(self, request, *args, **kwargs)
Ejemplo n.º 29
0
 def create_test(title, intro, parent=None):
     if (parent is None):
         parent = Page.get_first_root_node()
     project_idx = ProjectIndexPage(title=title, intro=intro,
                                    slug=text.slugify(title))
     parent.add_child(instance=project_idx)
     return project_idx
Ejemplo n.º 30
0
 def create_test(title, lead, parent=None):
     if (parent is None):
         parent = Page.get_first_root_node()
     home = HomePage(heading=title, title=title, lead=lead,
                     slug=text.slugify(title))
     parent.add_child(instance=home)
     return home
Ejemplo n.º 31
0
def browse(request, parent_page_id=None):
    # Find parent page
    if parent_page_id:
        parent_page = get_object_or_404(Page, id=parent_page_id)
    else:
        parent_page = Page.get_first_root_node()

    # Get children of parent page
    pages = parent_page.get_children()

    # Filter them by page type
    # A missing or empty page_type parameter indicates 'all page types' (i.e. descendants of wagtailcore.page)
    page_type_string = request.GET.get('page_type') or 'wagtailcore.page'
    if page_type_string != 'wagtailcore.page':
        try:
            desired_classes = page_models_from_string(page_type_string)
        except (ValueError, LookupError):
            raise Http404

        # restrict the page listing to just those pages that:
        # - are of the given content type (taking into account class inheritance)
        # - or can be navigated into (i.e. have children)
        choosable_pages = filter_page_type(pages, desired_classes)
        descendable_pages = pages.filter(numchild__gt=0)
        pages = choosable_pages | descendable_pages
    else:
        desired_classes = (Page, )

    can_choose_root = request.GET.get('can_choose_root', False)

    # Parent page can be chosen if it is a instance of desired_classes
    parent_page.can_choose = issubclass(parent_page.specific_class or Page, desired_classes) and (can_choose_root or not parent_page.is_root())

    # Pagination
    # We apply pagination first so we don't need to walk the entire list
    # in the block below
    paginator, pages = paginate(request, pages, per_page=25)

    # Annotate each page with can_choose/can_decend flags
    for page in pages:
        if desired_classes == (Page, ):
            page.can_choose = True
        else:
            page.can_choose = issubclass(page.specific_class or Page, desired_classes)

        page.can_descend = page.get_children_count()

    # Render
    return render_modal_workflow(
        request,
        'wagtailadmin/chooser/browse.html', 'wagtailadmin/chooser/browse.js',
        shared_context(request, {
            'parent_page': parent_page,
            'pages': pages,
            'search_form': SearchForm(),
            'page_type_string': page_type_string,
            'page_type_names': [desired_class.get_verbose_name() for desired_class in desired_classes],
            'page_types_restricted': (page_type_string != 'wagtailcore.page')
        })
    )
Ejemplo n.º 32
0
 def create_test(title, intro, parent=None):
     if (parent is None):
         parent = Page.get_first_root_node()
     contact = ContactFormPage(title=title, intro=intro, thank_you_head='f',
                               thank_you_text='f', slug=text.slugify(title))
     parent.add_child(instance=contact)
     return contact
Ejemplo n.º 33
0
def node(name, show_in_menus=True, live=True):
    return Page(
        slug=name,
        title=name,
        show_in_menus=show_in_menus,
        live=live,
    )
Ejemplo n.º 34
0
def browse(request, parent_page_id=None):
    page_type = request.GET.get('page_type') or 'wagtailcore.page'
    content_type_app_name, content_type_model_name = page_type.split('.')

    is_searching = False

    try:
        content_type = ContentType.objects.get_by_natural_key(content_type_app_name, content_type_model_name)
    except ContentType.DoesNotExist:
        raise Http404
    desired_class = content_type.model_class()

    if 'q' in request.GET:
        search_form = SearchForm(request.GET)
        if search_form.is_valid() and search_form.cleaned_data['q']:
            pages = desired_class.objects.exclude(
                depth=1  # never include root
            ).filter(title__icontains=search_form.cleaned_data['q'])[:10]
            is_searching = True

    if not is_searching:
        if parent_page_id:
            parent_page = get_object_or_404(Page, id=parent_page_id)
        else:
            parent_page = Page.get_first_root_node()

        parent_page.can_choose = issubclass(parent_page.specific_class, desired_class)
        search_form = SearchForm()
        pages = parent_page.get_children()

    # restrict the page listing to just those pages that:
    # - are of the given content type (taking into account class inheritance)
    # - or can be navigated into (i.e. have children)

    shown_pages = []
    for page in pages:
        page.can_choose = issubclass(page.specific_class, desired_class)
        page.can_descend = page.get_children_count()

        if page.can_choose or page.can_descend:
            shown_pages.append(page)

    if is_searching:
        return render(request, 'wagtailadmin/chooser/_search_results.html', {
            'querystring': get_querystring(request),
            'searchform': search_form,
            'pages': pages,
            'is_searching': is_searching
        })

    return render_modal_workflow(request, 'wagtailadmin/chooser/browse.html', 'wagtailadmin/chooser/browse.js', {
        'allow_external_link': request.GET.get('allow_external_link'),
        'allow_email_link': request.GET.get('allow_email_link'),
        'querystring': get_querystring(request),
        'parent_page': parent_page,
        'pages': shown_pages,
        'search_form': search_form,
        'is_searching': False
    })
Ejemplo n.º 35
0
 def create_test(title, intro, parent=None):
     if (parent is None):
         parent = Page.get_first_root_node()
     project_idx = ProjectIndexPage(title=title,
                                    intro=intro,
                                    slug=text.slugify(title))
     parent.add_child(instance=project_idx)
     return project_idx
    def test_slug_scopes_to_site(self):
        home_page = Page.objects.get(slug='home')
        article_index_one = Page(title='First Index', slug='firstindex')
        article_index_two = Page(title='Second Index', slug='secondindex')
        home_page.add_child(instance=article_index_one)
        home_page.add_child(instance=article_index_two)

        article_one = Page(title='Article One', slug='articleone')
        article_two = Page(title='Article Two', slug='articletwo')

        article_index_one.add_child(instance=article_one)
        article_index_two.add_child(instance=article_two)

        result = slug_matches_one_page_exactly('/shows/articleone/',
                                               article_index_two)

        assert result is None
Ejemplo n.º 37
0
 def post_search(self, request, *args, **kwargs):
     search_query = request.GET.get('q', None)
     self.posts = self.get_posts()
     if search_query:
         self.posts = self.posts.filter(body__contains=search_query)
         self.search_term = search_query
         self.search_type = 'search'
     return Page.serve(self, request, *args, **kwargs)
    def test_multiple_matches_returns_best_matching_page(self):
        home_page = Page.objects.get(slug='home')
        better_matching_article = Page(title='Workzone with Bridget Masinga',
                                       slug='workzonewithbridgetmasinga',
                                       live=True,
                                       first_published_at=datetime.now())
        poorer_matching_article = Page(title='Bridget Masinga',
                                       slug='bridgetmasinga',
                                       live=True,
                                       first_published_at=datetime.now())
        home_page.add_child(instance=better_matching_article)
        home_page.add_child(instance=poorer_matching_article)

        result = suggest_page_from_misspelled_slug('/workzonbridgetmasing/',
                                                   home_page)

        assert better_matching_article in result
Ejemplo n.º 39
0
 def create_index_page(self, sitename):
     '''create_index_page'''
     root_page = Page.get_root_nodes()[0]
     index_page = JournalIndexPage(title="{} Index Page".format(sitename),
                                   intro="{} introduction".format(sitename))
     root_page.add_child(instance=index_page)
     index_page.save_revision().publish()
     return index_page
Ejemplo n.º 40
0
    def test_get_site__more_than_one(self):
        """
        If there are multiple sites in the database, `get_site` should raise
        a MultipleObjectsReturned exeption
        """
        # Create a second site with a new root page
        root_page = Page.add_root(instance=Page(title="Second Sight"))
        Site.objects.create(hostname='secondsight.com',
                            port=80,
                            root_page=root_page)

        with self.assertRaises(Site.MultipleObjectsReturned) as cm:
            get_site()

        self.assertEqual(cm.exception.args,
                         ("Foliage can't auto-determine the Wagtail Site. "
                          "More than one Site exists in the database!", ))
Ejemplo n.º 41
0
def test_auto_recache(root_page, example_svg_upload):
    page = Page(title="nnep", slug="nnep")
    page.set_url_path(root_page)
    root_page.add_child(instance=page)
    page.save()
    assert page.url

    map = ImageMap.objects.create(svg=example_svg_upload)
    map.regions.create(element_id='blue', link_page=page)
    map.recache_svg(save=True)
    assert 'nnep' in map.rendered_svg
    page.slug = 'ffflop'
    page.save()  # The `post_save` triggers will get called...
    assert 'ffflop' in ImageMap.objects.get(pk=map.pk).rendered_svg
Ejemplo n.º 42
0
    def test_can_create_page(self):
        parent = Page.get_root_nodes()[0]

        # Assert that a RecruitmentPage can be made here, with this POST data
        self.assertCanCreate(parent, RecruitmentPage, {
            'title': 'Apply now!',
            'title_sv': 'Ansök nu!',
            'slug': 'apply2',
        }, 'Recruitment pages can be created at the root')
Ejemplo n.º 43
0
    def handle(self, *args, **options):

        if options['content_path']:
            content_path = options['content_path']
        elif settings.BOOTSTRAP_CONTENT_DIR:
            content_path = settings.BOOTSTRAP_CONTENT_DIR
        else:
            raise CommandError("Pass --content <content dir>, where <content dir>/pages contain .yml files")

        if options['owner']:
            owner_user = User.objects.get(username=options['owner'])
        else:
            owner_user = None
            #raise CommandError("Pass --owner <username>, where <username> will be the content owner")

        dry_run = options['dry']

        contents = load_content(os.path.join(content_path, 'pages'))

        for site in Site.objects.all():
            site.delete()

        for page in Page.objects.filter(id__gt=1):
            page.delete()

        root = Page.get_first_root_node()
        content_root = RootNode('/', page_properties={}, parent_page=root)
        for page_attrs in contents:
            new_node = SiteNode(full_path=page_attrs['path'], page_properties=page_attrs)
            content_root.add_node(new_node)

        page_property_defaults = get_page_defaults(content_path)
        relation_mappings = get_relation_mappings(content_path)

        content_root.instantiate_page(owner_user=owner_user,
                                      page_property_defaults=page_property_defaults,
                                      relation_mappings=relation_mappings,
                                      dry_run=dry_run)

        sites = []
        for site in get_sites(content_path):
            sites.append(Site.objects.create(hostname=site['hostname'],
                                             port=int(site['port']),
                                             root_page=page_for_path(site['root_page'])))

        default_site = sites[0]
        default_site.is_default_site = True
        default_site.save()

        if dry_run:
            self.stdout.write("Dry run, exiting without making changes")
            return

        content_root.instantiate_deferred_models(owner_user=owner_user,
                                                 page_property_defaults=page_property_defaults,
                                                 relation_mappings=relation_mappings,
                                                 dry_run=dry_run)
Ejemplo n.º 44
0
    def get_template(self, request, *args, **kwargs):
        """
        Returns template name.
        """
        if self.template_name:
            return self.template_name

        # Fall back to standard page method.
        return Page.get_template(self, request, *args, **kwargs)
Ejemplo n.º 45
0
 def entries_search(self, request, *args, **kwargs):
     search_query = request.GET.get('q', None)
     self.entries = self.get_entries()
     if search_query:
         self.entries = self.entries.search(search_query)
         self.search_term = search_query
         self.search_type = _('search')
         Query.get(search_query).add_hit()
     return Page.serve(self, request, *args, **kwargs)
Ejemplo n.º 46
0
    def test_search_scopes_to_site_root_page(self):
        home_page = Page.objects.get(slug='home')
        root_article = Page(
            title='Justin Bieber',
            slug='justin-bieber'
        )
        non_root_article = Page(
            depth=0,
            path='0002',
            title='Justin Bieber Again',
            slug='justin-bieber-again'
        )
        home_page.add_child(instance=root_article)
        non_root_article.save()

        result = pg_full_text_search('Justin Bieber', home_page)

        assert list(result) == [root_article]
Ejemplo n.º 47
0
    def test_can_create_at(self):
        # Pages are not `is_creatable`, and should not be creatable
        self.assertFalse(Page.can_create_at(Page()))

        # SimplePage can be created under a simple page
        self.assertTrue(SimplePage.can_create_at(SimplePage()))

        # StandardIndex can be created under a Page, but not a SimplePage
        self.assertTrue(StandardIndex.can_create_at(Page()))
        self.assertFalse(StandardIndex.can_create_at(SimplePage()))

        # The Business pages are quite restrictive in their structure
        self.assertTrue(BusinessSubIndex.can_create_at(BusinessIndex()))
        self.assertTrue(BusinessChild.can_create_at(BusinessIndex()))
        self.assertTrue(BusinessChild.can_create_at(BusinessSubIndex()))

        self.assertFalse(BusinessChild.can_create_at(SimplePage()))
        self.assertFalse(BusinessSubIndex.can_create_at(SimplePage()))
Ejemplo n.º 48
0
 def entries_search(self, request, *args, **kwargs):
     search_query = request.GET.get('q', None)
     self.entries = self.get_entries()
     if search_query:
         self.entries = self.entries.search(search_query)
         self.search_term = search_query
         self.search_type = _('search')
         Query.get(search_query).add_hit()
     return Page.serve(self, request, *args, **kwargs)
Ejemplo n.º 49
0
def index(request, parent_page_id=None):
    if parent_page_id:
        parent_page = get_object_or_404(Page, id=parent_page_id)
    else:
        parent_page = Page.get_first_root_node()

    pages = parent_page.get_children().prefetch_related('content_type')

    # Get page ordering
    ordering = request.GET.get('ordering', '-latest_revision_created_at')
    if ordering not in [
        'title',
        '-title',
        'content_type',
        '-content_type',
        'live', '-live',
        'latest_revision_created_at',
        '-latest_revision_created_at',
        'ord'
    ]:
        ordering = '-latest_revision_created_at'

    if ordering == 'ord':
        # preserve the native ordering from get_children()
        pass
    elif ordering == 'latest_revision_created_at':
        # order by oldest revision first.
        # Special case NULL entries - these should go at the top of the list.
        # Do this by annotating with Count('latest_revision_created_at'),
        # which returns 0 for these
        pages = pages.annotate(
            null_position=Count('latest_revision_created_at')
        ).order_by('null_position', 'latest_revision_created_at')
    elif ordering == '-latest_revision_created_at':
        # order by oldest revision first.
        # Special case NULL entries - these should go at the end of the list.
        pages = pages.annotate(
            null_position=Count('latest_revision_created_at')
        ).order_by('-null_position', '-latest_revision_created_at')
    else:
        pages = pages.order_by(ordering)

    # Pagination
    # Don't paginate if sorting by page order - all pages must be shown to
    # allow drag-and-drop reordering
    do_paginate = ordering != 'ord'
    if do_paginate:
        paginator, pages = paginate(request, pages, per_page=50)

    return render(request, 'wagtailadmin/pages/index.html', {
        'parent_page': parent_page,
        'ordering': ordering,
        'pagination_query_params': "ordering=%s" % ordering,
        'pages': pages,
        'do_paginate': do_paginate,
    })
Ejemplo n.º 50
0
def preview_on_create(request, content_type_app_name, content_type_model_name, parent_page_id):
    # Receive the form submission that would typically be posted to the 'create' view. If submission is valid,
    # return the rendered page; if not, re-render the edit form
    try:
        content_type = ContentType.objects.get_by_natural_key(content_type_app_name, content_type_model_name)
    except ContentType.DoesNotExist:
        raise Http404

    page_class = content_type.model_class()
    page = page_class()
    edit_handler_class = get_page_edit_handler(page_class)
    form_class = edit_handler_class.get_form_class(page_class)

    form = form_class(request.POST, request.FILES, instance=page)

    if form.is_valid():
        form.save(commit=False)

        # ensure that our unsaved page instance has a suitable url set
        parent_page = get_object_or_404(Page, id=parent_page_id).specific
        page.set_url_path(parent_page)

        # Set treebeard attributes
        page.depth = parent_page.depth + 1
        page.path = Page._get_children_path_interval(parent_page.path)[1]

        # This view will generally be invoked as an AJAX request; as such, in the case of
        # an error Django will return a plaintext response. This isn't what we want, since
        # we will be writing the response back to an HTML page regardless of success or
        # failure - as such, we strip out the X-Requested-With header to get Django to return
        # an HTML error response
        request.META.pop('HTTP_X_REQUESTED_WITH', None)

        try:
            display_mode = request.GET['mode']
        except KeyError:
            display_mode = page.get_page_modes()[0][0]
        response = page.show_as_mode(display_mode)

        response['X-Wagtail-Preview'] = 'ok'
        return response

    else:
        edit_handler = edit_handler_class(instance=page, form=form)
        parent_page = get_object_or_404(Page, id=parent_page_id).specific

        response = render(request, 'wagtailadmin/pages/create.html', {
            'content_type': content_type,
            'page_class': page_class,
            'parent_page': parent_page,
            'edit_handler': edit_handler,
            'display_modes': page.get_page_modes(),
        })
        response['X-Wagtail-Preview'] = 'error'
        return response
Ejemplo n.º 51
0
 def entries_by_date(self, request, year, month=None, day=None, *args, **kwargs):
     self.entries = self.get_entries().filter(date__year=year)
     self.search_type = _('date')
     self.search_term = year
     if month:
         self.entries = self.entries.filter(date__month=month)
         df = DateFormat(date(int(year), int(month), 1))
         self.search_term = df.format('F Y')
     if day:
         self.entries = self.entries.filter(date__day=day)
         self.search_term = date_format(date(int(year), int(month), int(day)))
     return Page.serve(self, request, *args, **kwargs)
Ejemplo n.º 52
0
 def by_date(self, request, year, month=None, day=None, *args, **kwargs):
     self.posts = self.queryset.filter(first_published_at__year=year)
     self.filter_type = _('date')
     self.filter_term = year
     if month:
         self.posts = self.posts.filter(date__month=month)
         df = DateFormat(date(int(year), int(month), 1))
         self.filter_term = df.format('F Y')
     if day:
         self.posts = self.posts.filter(date__day=day)
         self.filter_term = date_format(date(int(year), int(month), int(day)))
     return Page.serve(self, request, *args, **kwargs)
Ejemplo n.º 53
0
    def get_template(self, request, *args, **kwargs):
        """
        Returns template name.

        :param request: the request instance.
        :rtype: str.
        """
        if self.template_name:
            return self.template_name

        # Fall back to standard page method.
        return Page.get_template(self, request, *args, **kwargs)
Ejemplo n.º 54
0
    def setUp(self):
        self.site_2_page = SimplePage(
            title="Site 2 page",
            slug="site_2_page",
            content="Hello",
        )
        Page.get_first_root_node().add_child(instance=self.site_2_page)
        self.site_2_subpage = SimplePage(
            title="Site 2 subpage",
            slug="site_2_subpage",
            content="Hello again",
        )
        self.site_2_page.add_child(instance=self.site_2_subpage)

        self.site_2 = Site.objects.create(
            hostname='example.com',
            port=8080,
            root_page=Page.objects.get(pk=self.site_2_page.pk),
            is_default_site=False
        )
        self.about_us_page = SimplePage.objects.get(url_path='/home/about-us/')
Ejemplo n.º 55
0
    def handle_noargs(self, **options):
        problems_found = False

        for page in Page.objects.all():
            try:
                page.specific
            except ObjectDoesNotExist:
                print "Page %d (%s) is missing a subclass record; deleting." % (page.id, page.title)
                problems_found = True
                page.delete()

        (_, _, _, bad_depth, bad_numchild) = Page.find_problems()
        if bad_depth:
            print "Incorrect depth value found for pages: %r" % bad_depth
        if bad_numchild:
            print "Incorrect numchild value found for pages: %r" % bad_numchild

        if bad_depth or bad_numchild:
            Page.fix_tree(destructive=False)
            problems_found = True

        remaining_problems = Page.find_problems()
        if any(remaining_problems):
            print "Remaining problems (cannot fix automatically):"
            (bad_alpha, bad_path, orphans, bad_depth, bad_numchild) = remaining_problems
            if bad_alpha:
                print "Invalid characters found in path for pages: %r" % bad_alpha
            if bad_path:
                print "Invalid path length found for pages: %r" % bad_path
            if orphans:
                print "Orphaned pages found: %r" % orphans
            if bad_depth:
                print "Incorrect depth value found for pages: %r" % bad_depth
            if bad_numchild:
                print "Incorrect numchild value found for pages: %r" % bad_numchild

        elif problems_found:
            print "All problems fixed."
        else:
            print "No problems found."
Ejemplo n.º 56
0
    def test_create_news(self):
        self.assertEqual(NewsStory.objects.count(), 0)
        root = Page.add_root(title='Root page')

        news_folder = pkg_resources.resource_filename(
            'akllt', 'tests/fixtures/naujienos'
        )
        news = import_news(news_folder)
        for news_story in news:
            root.add_child(instance=NewsStory(
                title=news_story['title'],
                date=news_story['date'],
                blurb=news_story['blurb'],
                body=news_story['body'],
            ))
Ejemplo n.º 57
0
def preview_on_create(request, content_type_app_name, content_type_model_name, parent_page_id):
    # Receive the form submission that would typically be posted to the 'create' view. If submission is valid,
    # return the rendered page; if not, re-render the edit form
    try:
        content_type = ContentType.objects.get_by_natural_key(content_type_app_name, content_type_model_name)
    except ContentType.DoesNotExist:
        raise Http404

    page_class = content_type.model_class()
    page = page_class()
    edit_handler_class = get_page_edit_handler(page_class)
    form_class = edit_handler_class.get_form_class(page_class)

    form = form_class(request.POST, request.FILES, instance=page)

    if form.is_valid():
        form.save(commit=False)

        # ensure that our unsaved page instance has a suitable url set
        parent_page = get_object_or_404(Page, id=parent_page_id).specific
        page.set_url_path(parent_page)

        # Set treebeard attributes
        page.depth = parent_page.depth + 1
        page.path = Page._get_children_path_interval(parent_page.path)[1]

        preview_mode = request.GET.get("mode", page.default_preview_mode)
        response = page.serve_preview(page.dummy_request(), preview_mode)
        response["X-Wagtail-Preview"] = "ok"
        return response

    else:
        edit_handler = edit_handler_class(instance=page, form=form)
        parent_page = get_object_or_404(Page, id=parent_page_id).specific

        response = render(
            request,
            "wagtailadmin/pages/create.html",
            {
                "content_type": content_type,
                "page_class": page_class,
                "parent_page": parent_page,
                "edit_handler": edit_handler,
                "preview_modes": page.preview_modes,
            },
        )
        response["X-Wagtail-Preview"] = "error"
        return response
Ejemplo n.º 58
0
    def test_can_create_at(self):
        # Pages are not `is_creatable`, and should not be creatable
        self.assertFalse(Page.can_create_at(Page()))

        # SimplePage can be created under a simple page
        self.assertTrue(SimplePage.can_create_at(SimplePage()))

        # StandardIndex can be created under a Page, but not a SimplePage
        self.assertTrue(StandardIndex.can_create_at(Page()))
        self.assertFalse(StandardIndex.can_create_at(SimplePage()))

        # The Business pages are quite restrictive in their structure
        self.assertTrue(BusinessSubIndex.can_create_at(BusinessIndex()))
        self.assertTrue(BusinessChild.can_create_at(BusinessIndex()))
        self.assertTrue(BusinessChild.can_create_at(BusinessSubIndex()))

        self.assertFalse(BusinessChild.can_create_at(SimplePage()))
        self.assertFalse(BusinessSubIndex.can_create_at(SimplePage()))