Python wagtail.core.models.Page() Examples

The following are 30 code examples of wagtail.core.models.Page(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module wagtail.core.models , or try the search function .
Example #1
Source File: test_edit_page.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_post_edit_form(self):
        post_data = {
            'title': "My lovely index",
            'slug': 'my-lovely-index',
            'advert_placements-TOTAL_FORMS': '2',
            'advert_placements-INITIAL_FORMS': '1',
            'advert_placements-MAX_NUM_FORMS': '1000',
            'advert_placements-0-advert': '1',
            'advert_placements-0-colour': 'yellow',
            'advert_placements-0-id': self.index_page.advert_placements.first().id,
            'advert_placements-1-advert': '1',
            'advert_placements-1-colour': 'purple',
            'advert_placements-1-id': '',
            'action-publish': "Publish",
        }
        response = self.client.post(reverse('wagtailadmin_pages:edit', args=(self.index_page.id, )), post_data)

        # Should be redirected to explorer
        self.assertRedirects(response, reverse('wagtailadmin_explore', args=(self.root_page.id, )))

        # Find the page and check it
        page = Page.objects.get(id=self.index_page.id).specific
        self.assertEqual(page.advert_placements.count(), 2)
        self.assertEqual(page.advert_placements.all()[0].advert.text, 'test_advert')
        self.assertEqual(page.advert_placements.all()[1].advert.text, 'test_advert') 
Example #2
Source File: test_reports_views.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_xlsx_export(self):

        self.page = Page.objects.first()
        self.page.locked = True
        self.page.locked_by = self.user
        self.page.locked_at = '2013-02-01T12:00:00.000Z'
        self.page.latest_revision_created_at = '2013-01-01T12:00:00.000Z'
        self.page.save()

        response = self.get(params={'export': 'xlsx'})

        # Check response - the locked page info should be in it
        self.assertEqual(response.status_code, 200)
        workbook_data = response.getvalue()
        worksheet = load_workbook(filename=BytesIO(workbook_data))['Sheet1']
        cell_array = [[cell.value for cell in row] for row in worksheet.rows]
        self.assertEqual(cell_array[0], ['Title', 'Updated', 'Status', 'Type', 'Locked At', 'Locked By'])
        self.assertEqual(cell_array[1], ['Root', datetime.datetime(2013, 1, 1, 12, 0), 'live', 'Page', datetime.datetime(2013, 2, 1, 12, 0), 'test@email.com'])
        self.assertEqual(len(cell_array), 2) 
Example #3
Source File: wagtail_hooks.py    From wagtail-personalisation with MIT License 6 votes vote down vote up
def segment_user(page, request, serve_args, serve_kwargs):
    """Apply a segment to a visitor before serving the page.

    :param page: The page being served
    :type page: wagtail.core.models.Page
    :param request: The http request
    :type request: django.http.HttpRequest

    """
    adapter = get_segment_adapter(request)
    adapter.refresh()

    forced_segment = request.GET.get('segment', None)
    if request.user.is_superuser and forced_segment is not None:
        segment = models.Segment.objects.filter(pk=forced_segment).first()
        if segment:
            adapter.set_segments([segment]) 
Example #4
Source File: test_edit_handlers.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_get_form_for_model(self):
        EventPageForm = get_form_for_model(EventPage, form_class=WagtailAdminPageForm)
        form = EventPageForm()

        # form should be a subclass of WagtailAdminModelForm
        self.assertTrue(issubclass(EventPageForm, WagtailAdminModelForm))
        # form should contain a title field (from the base Page)
        self.assertEqual(type(form.fields['title']), forms.CharField)
        # and 'date_from' from EventPage
        self.assertEqual(type(form.fields['date_from']), forms.DateField)
        # the widget should be overridden with AdminDateInput as per FORM_FIELD_OVERRIDES
        self.assertEqual(type(form.fields['date_from'].widget), AdminDateInput)

        # treebeard's 'path' field should be excluded
        self.assertNotIn('path', form.fields)

        # all child relations become formsets by default
        self.assertIn('speakers', form.formsets)
        self.assertIn('related_links', form.formsets) 
Example #5
Source File: misc.py    From wagtailmenus with MIT License 6 votes vote down vote up
def validate_supplied_values(tag, max_levels=None, parent_page=None,
                             menuitem_or_page=None):
    if max_levels is not None:
        if max_levels not in (1, 2, 3, 4, 5):
            raise ValueError(
                "The `%s` tag expects `max_levels` to be an integer value "
                "between 1 and 5. Please review your template." % tag
            )
    if parent_page is not None:
        if not isinstance(parent_page, Page):
            raise ValueError(
                "The `%s` tag expects `parent_page` to be a `Page` instance. "
                "A value of type `%s` was supplied." %
                (tag, parent_page.__class__)
            )
    if menuitem_or_page is not None:
        if not isinstance(menuitem_or_page, (Page, MenuItem)):
            raise ValueError(
                "The `%s` tag expects `menuitem_or_page` to be a `Page` or "
                "`MenuItem` instance. A value of type `%s` was supplied." %
                (tag, menuitem_or_page.__class__)
            ) 
Example #6
Source File: test_reports_views.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_simple(self):
        response = self.get()
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'wagtailadmin/reports/locked_pages.html')

        # Initially there should be no locked pages
        self.assertContains(response, "No locked pages found.")

        self.page = Page.objects.first()
        self.page.locked = True
        self.page.locked_by = self.user
        self.page.locked_at = timezone.now()
        self.page.save()

        # Now the listing should contain our locked page
        response = self.get()
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'wagtailadmin/reports/locked_pages.html')
        self.assertNotContains(response, "No locked pages found.")
        self.assertContains(response, self.page.title) 
Example #7
Source File: test_edit_handlers.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_page_with_inline_model_with_tabbed_panel_only(self):
        """Test that checks will warn against setting single tabbed panel on InlinePanel model"""

        EventPageSpeaker.settings_panels = [FieldPanel('first_name'), FieldPanel('last_name')]

        warning = checks.Warning(
            "EventPageSpeaker.settings_panels will have no effect on InlinePanel model editing",
            hint="""Ensure that EventPageSpeaker uses `panels` instead of `settings_panels`.
There are no tabs on non-Page model editing within InlinePanels.""",
            obj=EventPageSpeaker,
            id=self.warning_id,
        )

        checks_results = self.get_checks_result()

        self.assertIn(warning, checks_results)

        delattr(EventPageSpeaker, 'settings_panels') 
Example #8
Source File: test_edit_handlers.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def setUp(self):
        self.request = RequestFactory().get('/')
        user = AnonymousUser()  # technically, Anonymous users cannot access the admin
        self.request.user = user

        model = PageChooserModel  # a model with a foreign key to Page which we want to render as a page chooser

        # a PageChooserPanel class that works on PageChooserModel's 'page' field
        self.edit_handler = (ObjectList([PageChooserPanel('page')])
                             .bind_to(model=PageChooserModel,
                                      request=self.request))
        self.my_page_chooser_panel = self.edit_handler.children[0]

        # build a form class containing the fields that MyPageChooserPanel wants
        self.PageChooserForm = self.edit_handler.get_form_class()

        # a test instance of PageChooserModel, pointing to the 'christmas' page
        self.christmas_page = Page.objects.get(slug='christmas')
        self.events_index_page = Page.objects.get(slug='events')
        self.test_instance = model.objects.create(page=self.christmas_page)

        self.form = self.PageChooserForm(instance=self.test_instance)
        self.page_chooser_panel = self.my_page_chooser_panel.bind_to(
            instance=self.test_instance, form=self.form) 
Example #9
Source File: test_reports_views.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_csv_export(self):

        self.page = Page.objects.first()
        self.page.locked = True
        self.page.locked_by = self.user
        self.page.locked_at = '2013-02-01T12:00:00.000Z'
        self.page.latest_revision_created_at = '2013-01-01T12:00:00.000Z'
        self.page.save()

        response = self.get(params={'export': 'csv'})

        # Check response
        self.assertEqual(response.status_code, 200)
        data_lines = response.getvalue().decode().split("\n")
        self.assertEqual(data_lines[0], 'Title,Updated,Status,Type,Locked At,Locked By\r')
        self.assertEqual(data_lines[1], 'Root,2013-01-01 12:00:00+00:00,live,Page,2013-02-01 12:00:00+00:00,test@email.com\r') 
Example #10
Source File: tests.py    From wagtail_blog with Apache License 2.0 6 votes vote down vote up
def test_index(self):
        url = self.blog_index.url
        res = self.client.get(url)
        self.assertEqual(res.status_code, 200)

        blog_page = self.blog_index.add_child(
            instance=BlogPage(
                title="Blog Page",
                slug="blog_page1",
                search_description="x",
                owner=self.user,
            )
        )
        url = blog_page.url
        res = self.client.get(url)
        self.assertContains(res, "Blog Page") 
Example #11
Source File: tests.py    From wagtail_blog with Apache License 2.0 6 votes vote down vote up
def test_latest_entries_feed(self):
        self.blog_index.add_child(
            instance=BlogPage(
                title="Blog Page",
                slug="blog_page1",
                search_description="x",
                owner=self.user,
            )
        )
        res = self.client.get(
            "{0}{1}/rss/".format(self.blog_index.url, self.blog_index.slug)
        )
        self.assertContains(res, "Blog Page")
        self.assertContains(res, "<rss")
        self.assertContains(res, 'version="2.0"')
        self.assertContains(res, "</rss>") 
Example #12
Source File: tests.py    From wagtail_blog with Apache License 2.0 6 votes vote down vote up
def test_latest_entries_feed_atom(self):
        self.blog_index.add_child(
            instance=BlogPage(
                title="Blog Page",
                slug="blog_page1",
                search_description="x",
                owner=self.user,
            )
        )
        res = self.client.get(
            "{0}{1}/atom/".format(self.blog_index.url, self.blog_index.slug)
        )
        self.assertContains(res, "Blog Page")
        self.assertContains(res, "<feed")
        self.assertContains(res, 'xmlns="http://' 'www.w3.org/2005/Atom"')
        self.assertContains(res, "</feed>") 
Example #13
Source File: tests.py    From securethenews with GNU Affero General Public License v3.0 6 votes vote down vote up
def setUp(self):
        home_page = Page.objects.get(slug='home')

        blog_index_page = BlogIndexPage(
            title='Blog',
            slug='blog',
            show_in_menus=True
        )
        home_page.add_child(instance=blog_index_page)

        blog_posts = [
            BlogPost(title='First Blog Post',
                     slug='first-blog-post',
                     date=datetime.date.today(),
                     byline='Author'),
            BlogPost(title='Second Blog Post',
                     slug='second-blog-post',
                     date=datetime.date.today(),
                     byline='Author')
        ]

        for blog_post in blog_posts:
            blog_index_page.add_child(instance=blog_post) 
Example #14
Source File: benches.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def setUp(self):
        self.root_page = Page.objects.get(id=1)

        # Add a site so the URLs render correctly
        Site.objects.create(is_default_site=True, root_page=self.root_page)

        # Create a large piece of body text
        body = '[' + ','.join(['{"type": "text", "value": "%s"}' % ('foo' * 2000)] * 100) + ']'

        # Create 50 simple pages with long content fields
        for i in range(50):
            self.root_page.add_child(instance=StreamPage(
                title="Page {}".format(i + 1),
                slug=str(i + 1),
                body=body,
            ))

        self.login() 
Example #15
Source File: test_edit_page.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_post_create_form(self):
        post_data = {
            'title': "New index!",
            'slug': 'new-index',
            'advert_placements-TOTAL_FORMS': '1',
            'advert_placements-INITIAL_FORMS': '0',
            'advert_placements-MAX_NUM_FORMS': '1000',
            'advert_placements-0-advert': '1',
            'advert_placements-0-colour': 'yellow',
            'advert_placements-0-id': '',
        }
        response = self.client.post(
            reverse('wagtailadmin_pages:add', args=('tests', 'standardindex', self.root_page.id)), post_data
        )

        # Find the page and check it
        page = Page.objects.get(path__startswith=self.root_page.path, slug='new-index').specific

        # Should be redirected to edit page
        self.assertRedirects(response, reverse('wagtailadmin_pages:edit', args=(page.id, )))

        self.assertEqual(page.advert_placements.count(), 1)
        self.assertEqual(page.advert_placements.first().advert.text, 'test_advert') 
Example #16
Source File: test_edit_page.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_after_edit_page_hook(self):
        def hook_func(request, page):
            self.assertIsInstance(request, HttpRequest)
            self.assertEqual(page.id, self.child_page.id)

            return HttpResponse("Overridden!")

        with self.register_hook('after_edit_page', hook_func):
            post_data = {
                'title': "I've been edited!",
                'content': "Some content",
                'slug': 'hello-world-new',
                'action-publish': "Publish",
            }
            response = self.client.post(
                reverse('wagtailadmin_pages:edit', args=(self.child_page.id, )), post_data
            )

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.content, b"Overridden!")

        # page should be edited
        self.assertEqual(Page.objects.get(id=self.child_page.id).title, "I've been edited!") 
Example #17
Source File: test_edit_page.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_before_edit_page_hook_post(self):
        def hook_func(request, page):
            self.assertIsInstance(request, HttpRequest)
            self.assertEqual(page.id, self.child_page.id)

            return HttpResponse("Overridden!")

        with self.register_hook('before_edit_page', hook_func):
            post_data = {
                'title': "I've been edited!",
                'content': "Some content",
                'slug': 'hello-world-new',
                'action-publish': "Publish",
            }
            response = self.client.post(
                reverse('wagtailadmin_pages:edit', args=(self.child_page.id, )), post_data
            )

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.content, b"Overridden!")

        # page should not be edited
        self.assertEqual(Page.objects.get(id=self.child_page.id).title, "Hello world!") 
Example #18
Source File: views.py    From longclaw with MIT License 6 votes vote down vote up
def requests_admin(request, pk):
    """Table display of each request for a given product.

    Allows the given Page pk to refer to a direct parent of
    the ProductVariant model or be the ProductVariant model itself.
    This allows for the standard longclaw product modelling philosophy where
    ProductVariant refers to the actual product (in the case where there is
    only 1 variant) or to be variants of the product page.
    """
    page = Page.objects.get(pk=pk).specific
    if hasattr(page, 'variants'):
        requests = ProductRequest.objects.filter(
            variant__in=page.variants.all()
        )
    else:
        requests = ProductRequest.objects.filter(variant=page)
    return render(
        request,
        "productrequests/requests_admin.html",
        {'page': page, 'requests': requests}
    ) 
Example #19
Source File: test_edit_page.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_page_edit_post(self):
        # Tests simple editing
        post_data = {
            'title': "I've been edited!",
            'content': "Some content",
            'slug': 'hello-world',
        }
        response = self.client.post(reverse('wagtailadmin_pages:edit', args=(self.child_page.id, )), post_data)

        # Should be redirected to edit page
        self.assertRedirects(response, reverse('wagtailadmin_pages:edit', args=(self.child_page.id, )))

        # The page should have "has_unpublished_changes" flag set
        child_page_new = SimplePage.objects.get(id=self.child_page.id)
        self.assertTrue(child_page_new.has_unpublished_changes)

        # Page fields should not be changed (because we just created a new draft)
        self.assertEqual(child_page_new.title, self.child_page.title)
        self.assertEqual(child_page_new.content, self.child_page.content)
        self.assertEqual(child_page_new.slug, self.child_page.slug)

        # The draft_title should have a new title
        self.assertEqual(child_page_new.draft_title, post_data['title']) 
Example #20
Source File: test_move_page.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_after_move_page_hook(self):
        def hook_func(request, page):
            self.assertIsInstance(request, HttpRequest)
            self.assertIsInstance(page.specific, SimplePage)

            return HttpResponse("Overridden!")

        with self.register_hook('after_move_page', hook_func):
            response = self.client.post(reverse('wagtailadmin_pages:move_confirm', args=(self.test_page_a.id, self.section_b.id)))

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.content, b"Overridden!")

        # page should be moved
        self.assertEqual(
            Page.objects.get(id=self.test_page_a.id).get_parent().id,
            self.section_b.id
        ) 
Example #21
Source File: test_move_page.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_before_move_page_hook_post(self):
        def hook_func(request, page, destination):
            self.assertIsInstance(request, HttpRequest)
            self.assertIsInstance(page.specific, SimplePage)
            self.assertIsInstance(destination.specific, SimplePage)

            return HttpResponse("Overridden!")

        with self.register_hook('before_move_page', hook_func):
            response = self.client.post(reverse('wagtailadmin_pages:move_confirm', args=(self.test_page_a.id, self.section_b.id)))

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.content, b"Overridden!")

        # page should not be moved
        self.assertEqual(
            Page.objects.get(id=self.test_page_a.id).get_parent().id,
            self.section_a.id
        ) 
Example #22
Source File: widgets.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def render_js_init(self, id_, name, value):
        if isinstance(value, Page):
            page = value
        else:
            # Value is an ID look up object
            model_class = self._get_lowest_common_page_class()
            page = self.get_instance(model_class, value)

        parent = page.get_parent() if page else None

        return "createPageChooser({id}, {model_names}, {parent}, {can_choose_root}, {user_perms});".format(
            id=json.dumps(id_),
            model_names=json.dumps([
                '{app}.{model}'.format(
                    app=model._meta.app_label,
                    model=model._meta.model_name)
                for model in self.target_models
            ]),
            parent=json.dumps(parent.id if parent else None),
            can_choose_root=('true' if self.can_choose_root else 'false'),
            user_perms=json.dumps(self.user_perms),
        ) 
Example #23
Source File: test_explorer_view.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def setUp(self):
        # Find root page
        self.root_page = Page.objects.get(id=1)

        # Find page with an associated site
        self.site_page = Page.objects.get(id=2)

        # Add another top-level page (which will have no corresponding site record)
        self.no_site_page = SimplePage(
            title="Hello world!",
            slug="hello-world",
            content="hello",
        )
        self.root_page.add_child(instance=self.no_site_page)

    # Tests for users that have both add-site permission, and explore permission at the given view;
    # warning messages should include advice re configuring sites 
Example #24
Source File: test_moderation.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_approve_moderation_when_later_revision_exists(self):
        self.page.title = "Goodbye world!"
        self.page.save_revision(user=self.submitter, submitted_for_moderation=False)

        response = self.client.post(reverse('wagtailadmin_pages:approve_moderation', args=(self.revision.id, )))

        # Check that the user was redirected to the dashboard
        self.assertRedirects(response, reverse('wagtailadmin_home'))

        page = Page.objects.get(id=self.page.id)
        # Page must be live
        self.assertTrue(page.live, "Approving moderation failed to set live=True")
        # Page content should be the submitted version, not the published one
        self.assertEqual(page.title, "Hello world!")
        # Page should still have unpublished changes
        self.assertTrue(
            page.has_unpublished_changes,
            "has_unpublished_changes incorrectly cleared on approve_moderation when a later revision exists"
        ) 
Example #25
Source File: test_edit_page.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_first_published_at_editable(self):
        """Test that we can update the first_published_at via the Page edit form,
        for page models that expose it."""

        # Add child page, of a type which has first_published_at in its form
        child_page = ManyToManyBlogPage(
            title="Hello world!",
            slug="hello-again-world",
            body="hello",
        )
        self.root_page.add_child(instance=child_page)
        child_page.save_revision().publish()
        self.child_page = ManyToManyBlogPage.objects.get(id=child_page.id)

        initial_delta = self.child_page.first_published_at - timezone.now()

        first_published_at = timezone.now() - datetime.timedelta(days=2)

        post_data = {
            'title': "I've been edited!",
            'body': "Some content",
            'slug': 'hello-again-world',
            'action-publish': "Publish",
            'first_published_at': submittable_timestamp(first_published_at),
        }
        self.client.post(reverse('wagtailadmin_pages:edit', args=(self.child_page.id, )), post_data)

        # Get the edited page.
        child_page_new = ManyToManyBlogPage.objects.get(id=self.child_page.id)

        # first_published_at should have changed.
        new_delta = child_page_new.first_published_at - timezone.now()
        self.assertNotEqual(new_delta.days, initial_delta.days)
        # first_published_at should be 3 days ago.
        self.assertEqual(new_delta.days, -3) 
Example #26
Source File: test_edit_page.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_create_inaccessible(self):
        """
        Create a page outside of the site root, check the flash message does
        not have a "View live" button.
        """
        response, page = self._create_page(Page.objects.get(pk=1))
        self.assertIsNone(page.url)
        self.assertFalse(any(
            'View live' in message.message
            for message in response.context['messages'])) 
Example #27
Source File: test_edit_page.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_approve_inaccessible(self):
        """
        Edit a page outside of the site root, check the flash message does
        not have a "View live" button.
        """
        response, page = self._approve_page(Page.objects.get(pk=1))
        self.assertIsNone(page.url)
        self.assertFalse(any(
            'View live' in message.message
            for message in response.context['messages'])) 
Example #28
Source File: test_edit_page.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_approve_accessible(self):
        """
        Edit a page under the site root, check the flash message has a valid
        "View live" button.
        """
        response, page = self._approve_page(Page.objects.get(pk=2))
        self.assertIsNotNone(page.url)
        self.assertTrue(any(
            'View live' in message.message and page.url in message.message
            for message in response.context['messages'])) 
Example #29
Source File: test_edit_page.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        self.root_page = Page.objects.get(id=2)
        child_page = SingleEventPage(
            title="Test Event", slug="test-event", location="test location",
            cost="10", date_from=datetime.datetime.now(),
            audience=EVENT_AUDIENCE_CHOICES[0][0])
        self.root_page.add_child(instance=child_page)
        child_page.save_revision().publish()
        self.child_page = SingleEventPage.objects.get(id=child_page.id)
        self.user = self.login() 
Example #30
Source File: test_edit_page.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        self.events_index = Page.objects.get(url_path='/home/events/')
        self.christmas_page = EventPage.objects.get(url_path='/home/events/christmas/')
        self.speaker = self.christmas_page.speakers.first()
        self.speaker.awards.create(
            name="Beard Of The Year", date_awarded=datetime.date(1997, 12, 25)
        )
        self.speaker.save()
        self.user = self.login()