我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用wagtail.wagtailcore.models.Page()。
def delete_submission(request, page_id, submission_id): if not get_surveys_for_user(request.user).filter(id=page_id).exists(): raise PermissionDenied page = get_object_or_404(Page, id=page_id).specific submission = get_object_or_404(page.get_submission_class(), id=submission_id) if request.method == 'POST': submission.delete() messages.success(request, _("Submission deleted.")) return redirect('wagtailsurveys:list_submissions', page_id) return render(request, 'wagtailsurveys/confirm_delete.html', { 'page': page, 'submission': submission })
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)
def full_clean(self, *args, **kwargs): # autogenerate slugs for non-empty title translation for lang_code in mt_settings.AVAILABLE_LANGUAGES: title_field = build_localized_fieldname('title', lang_code) slug_field = build_localized_fieldname('slug', lang_code) title = getattr(self, title_field) slug = getattr(self, slug_field) if title and not slug: if DJANGO_VERSION >= (1, 9): base_slug = slugify(title, allow_unicode=True) else: base_slug = slugify(title) if base_slug: setattr(self, slug_field, self._get_autogenerated_lang_slug(base_slug, lang_code)) super(Page, self).full_clean(*args, **kwargs)
def move(self, target, pos=None): old_self = Page.objects.get(id=self.id) super(Page, self).move(target, pos=pos) new_self = Page.objects.get(id=self.id) # go through slugs to make sure they're available in new parent # and auto-update if necessary for lang_code in mt_settings.AVAILABLE_LANGUAGES: slug_attr = build_localized_fieldname('slug', lang_code) slug = getattr(new_self, slug_attr) if slug: slug = new_self._get_autogenerated_lang_slug(slug, lang_code) setattr(new_self, slug_attr, slug) new_self.set_url_path(new_self.get_parent()) new_self.save() new_self._update_descendant_lang_url_paths(old_self) logger.info("Page moved: \"%s\" id=%d path=%s", self.title, self.id, self.url_path)
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} )
def revisions_view(request, page_id, revision_id): """ Redirects to a frontend preview page of type: `<frontend-preview-url>/<signature>/<page-id>/<revision-id>` Where: - frontend-preview-url: settings.FRONTEND_PREVIEW_URL - signature: see the generate_preview_signature method - page-id: id of the page - revision-id: id of the revision """ if not settings.FRONTEND_PREVIEW_URL: return HttpResponse(_('Please set FRONTEND_PREVIEW_URL in your settings.py')) page = get_object_or_404(Page, id=page_id).specific revision = get_object_or_404(page.revisions, id=revision_id) signature = generate_preview_signature(page.id, revision.id) return redirect( settings.FRONTEND_PREVIEW_URL.format( signature=signature.decode(), page_id=page.id, revision_id=revision.id ) )
def get_site_root(context): """Returns the site root Page, not the implementation-specific model used. :rtype: `wagtail.wagtailcore.models.Page` """ return context['request'].site.root_page
def slugurl(context, slug): """Returns the URL for the page that has the given slug.""" page = Page.objects.filter(slug=slug).first() if page: return pageurl(context, page) else: return None
def __init__(self, *args, **kwargs): """ Create fields dicts without any translation fields. """ # Extend local fields, this ensures that Wagtail Page models are always # extend on the local application, not on Wagtail itself (which would # cause us to need migrations on wagtailcore!) self.fields = list(self.fields) self.fields += [ 'search_description', 'seo_title', 'title', ] super(TranslationOptions, self).__init__(*args, **kwargs)
def select_winner(request, experiment_id, variation_id): if not request.user.has_perm('experiments.change_experiment'): raise PermissionDenied experiment = get_object_or_404(Experiment, pk=experiment_id) variation = get_object_or_404(Page, pk=variation_id) if request.method == 'POST': experiment.select_winner(variation) messages.success( request, _("Page '{0}' has been selected as the winning variation.").format(variation.title), ) return redirect('experiments:report', experiment.pk)
def preview_for_report(request, experiment_id, page_id): experiment = get_object_or_404(Experiment, pk=experiment_id) page = get_object_or_404(Page, id=page_id).specific if not page.permissions_for_user(request.user).can_publish(): raise PermissionDenied # hack the title and page-tree-related fields to match the control page impersonate_other_page(page, experiment.control_page) # pass in the real user request rather than page.dummy_request(), so that request.user # and request.revision_id will be picked up by the wagtail user bar return page.serve_preview(request, page.default_preview_mode)
def test_frontend_cache_invalidation(self, mock_purge_page_from_cache): """When a BlogPost is published or unpublished, we should invalidate the frontend cache for the corresponding BlogIndexPage.""" blog_index_page = BlogIndexPage.objects.first() new_blog_post = BlogPost( title='New Blog Post', slug='new-blog-post', date=datetime.date.today(), byline='Author' ) blog_index_page.add_child(instance=new_blog_post) # Publishing a BlogPost should trigger frontend cache invalidation for # the corresponding BlogIndexPage. # # XXX: For some reason, Wagtail uses the generic Page object as the # instance for the page_published signal, but uses the specific object # (e.g. BlogIndexPage) as the instance for the page_unpublished signal. # You can get the generic Page object from a specific object with # .page_ptr, or go the other way with .specific. For more, see: # http://docs.wagtail.io/en/v1.8/topics/pages.html#working-with-pages new_blog_post.save_revision().publish() mock_purge_page_from_cache.assert_called_once_with( blog_index_page.page_ptr) # Unpublishing the BlogPost should also trigger frontend cache # invalidation for the corresponding BlogIndexPage. mock_purge_page_from_cache.reset_mock() new_blog_post.unpublish() mock_purge_page_from_cache.assert_called_once_with(blog_index_page)
def test_page_str(self): page_block = PageBlock( page=Page(title='Title', slug='title'), block='path.to.block' ) self.assertEqual(str(page_block), '<Title, path.to.block>')
def get_url_for_object(object): """ """ if isinstance(object, Page): return object.url else: return object.get_absolute_uri()
def test_inheritance(self): self.assertTrue(issubclass(PageRedirection, Page))
def test_redirect_to_page(self): field = PageRedirection._meta.get_field('redirect_to_page') self.assertModelPKField(field, Page, models.PROTECT, False, False, '+') # view
def test_inheritance(self): self.assertTrue(issubclass(PagePlaceholder, Page))
def test_inheritance(self): self.assertTrue(issubclass(BasicPage, Page))
def test_fallback_wagtail_serve(self): site = Site.objects.get(is_default_site=True) root = site.root_page page = Page(title='wagtail title', slug='title') root.add_child(instance=page) page.save() page.save_revision().publish() fail_through = lambda request: wagtail_serve(request, request.path) view = TestView.as_view(flag_name=self.flag_name, condition=True, fallback=fail_through) response = view(self.request(path='/title')) self.assertContains(response, '<title>wagtail title</title>')
def url_path_fix(apps, schema_editor): # cannot use apps.get_model here # because Page instances wouldn't have set_url_path method from wagtail.wagtailcore.models import Page url_path_fields = get_translation_fields('url_path') for page in Page.objects.order_by('path').iterator(): page.set_url_path(page.get_parent()) # make sure descendant page url paths are not updated at this point # because it would fail page.save(update_fields=url_path_fields)
def handle(self, **options): fixtures_dir = os.path.join(settings.BASE_DIR, 'base', 'fixtures') fixture_file = os.path.join(fixtures_dir, 'bakerydemo.json') # Wagtail creates default Site and Page instances during install, but we already have # them in the data load. Remove the auto-generated ones. if Site.objects.filter(hostname='localhost').exists(): Site.objects.get(hostname='localhost').delete() if Page.objects.filter(title='Welcome to your new Wagtail site!').exists(): Page.objects.get(title='Welcome to your new Wagtail site!').delete() call_command('loaddata', fixture_file, verbosity=0) print("Awesome. Your data is loaded! The bakery's doors are almost ready to open...")
def setUp(self): super(TestMultipleSites, self).setUp() 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))
def view_draft(request, page_id): """ Redirects to revisions_view using the latest revision of the page with id == `page_id`. """ page = get_object_or_404(Page, id=page_id) revision = page.get_latest_revision() return redirect('wagtailadmin_pages:revisions_view', page.id, revision.id)
def test_used_image_document_get_usage(self): page = EventPage.objects.get(id=4) event_page_carousel_item = EventPageCarouselItem() event_page_carousel_item.page = page event_page_carousel_item.image = self.image event_page_carousel_item.save() self.assertTrue(issubclass(Page, type(self.image.get_usage()[0])))
def test_used_document_get_usage(self): doc = Document.objects.get(id=1) page = EventPage.objects.get(id=4) event_page_related_link = EventPageRelatedLink() event_page_related_link.page = page event_page_related_link.link_document = doc event_page_related_link.save() self.assertTrue(issubclass(Page, type(doc.get_usage()[0])))
def copy_page_view(request, page_id, segment_id): """Copy page with selected segment. If the page for the selected segment already exists the user will be redirected to that particular page. :param request: The http request :type request: django.http.HttpRequest :param page_id: The primary key of the page :type segment_id: int :param segment_id: The primary key of the segment :type segment_id: int :returns: A redirect to the new page :rtype: django.http.HttpResponseRedirect """ if request.user.has_perm('wagtailadmin.access_admin'): segment = get_object_or_404(Segment, pk=segment_id) page = get_object_or_404(Page, pk=page_id).specific metadata = page.personalisation_metadata variant_metadata = metadata.metadata_for_segments([segment]) if variant_metadata.exists(): variant = variant_metadata.first() else: variant = metadata.copy_for_segment(segment) edit_url = reverse('wagtailadmin_pages:edit', args=[variant.id]) return HttpResponseRedirect(edit_url) return HttpResponseForbidden()
def set_visit_count(page, request, serve_args, serve_kwargs): """Tests the provided rules to see if the request still belongs to a segment. :param page: The page being served :type page: wagtail.wagtailcore.models.Page :param request: The http request :type request: django.http.HttpRequest """ adapter = get_segment_adapter(request) adapter.add_page_visit(page)
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.wagtailcore.models.Page :param request: The http request :type request: django.http.HttpRequest """ adapter = get_segment_adapter(request) adapter.refresh()
def serve_variant(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.wagtailcore.models.Page :param request: The http request :type request: django.http.HttpRequest :returns: A variant if one is available for the visitor's segment, otherwise the original page :rtype: wagtail.wagtailcore.models.Page """ user_segments = [] if not isinstance(page, models.PersonalisablePageMixin): return adapter = get_segment_adapter(request) user_segments = adapter.get_segments() if user_segments: metadata = page.personalisation_metadata # TODO: This is never more then one page? (fix query count) metadata = metadata.metadata_for_segments(user_segments) if metadata: variant = metadata.first().variant.specific return variant.serve(request, *serve_args, **serve_kwargs)
def get_context(self): context = super(CorrectedPagesSummaryPanel, self).get_context() pages = utils.exclude_variants(Page.objects.all().specific()) context['total_pages'] = len(pages) - 1 return context
def test_blog_child_of_anything(self): """ Ensures that the Blog page can be child of any kind of Page """ self.assertCanCreateAt(Page, Blog)
def test_post_cannot_be_child_of_anything(self): """ Ensures that a Post page cannot be a child of a generic page """ self.assertCanNotCreateAt(Page, Post)
def test_post_cannot_have_children(self): """ Ensures that a Post page cannot have any kind of children """ self.assertCanNotCreateAt(Post, Page)
def test_static_page_child_of_anything(self): """ Ensures that a Static page can be child of any kind of Page """ self.assertCanCreateAt(Page, StaticPage)
def setUp(self): self.root_page = Page.objects.get(id=2) # Add child page self.child_page = SimplePage( title="foobarbaz", content="hello", ) self.root_page.add_child(instance=self.child_page)
def test_serialize(self): """The value of a ModelChooserBlock (a Page object) should serialize to an ID""" block = blocks.ModelChooserBlock('core_page') self.assertEqual(block.get_prep_value(self.child_page), self.child_page.id) # None should serialize to None self.assertEqual(block.get_prep_value(None), None)
def test_deserialize(self): """The serialized value of a ModelChooserBlock (an ID) should deserialize to a Page object""" block = blocks.ModelChooserBlock('core_page') self.assertEqual(isinstance(block.to_python(self.child_page.id), Page), isinstance(self.child_page, Page)) # None should deserialize to None self.assertEqual(block.to_python(None), None)
def test_to_python(self): block = blocks.ModelChooserBlock('core_page') test_page = self.child_page value = block.to_python(test_page.pk) self.assertEqual(isinstance(value, Page), isinstance(test_page, Page)) self.assertEqual(block.to_python(None), None)
def test_target_model(self): block = blocks.ModelChooserBlock('core_page') self.assertEqual(block.target_model, Page)
def test_get_target_model_string(self): widget = widgets.ModelChooserWidget('wagtailcore.Page', **self.get_widget_options()) model = widget.target_model() self.assertEqual(model.__class__, Page)
def test_get_target_model_class(self): widget = widgets.ModelChooserWidget(Page, **self.get_widget_options()) model = widget.target_model() self.assertEqual(model.__class__, Page)
def test_get_instance_none_value(self): widget = widgets.ModelChooserWidget(Page, **self.get_widget_options()) self.assertFalse(widget.get_instance(''))
def test_get_instance_page_value(self): widget = widgets.ModelChooserWidget(Page, **self.get_widget_options()) self.assertEqual(widget.get_instance(2), self.root_page)
def test_get_instance_no_page_value_is_none(self): widget = widgets.ModelChooserWidget(Page, **self.get_widget_options()) self.assertEqual(widget.get_instance(999), None)
def test_get_internal_value(self): id_ = uuid.uuid4() class Stub: pk = None stub = Stub() stub.pk = id_ widget = widgets.ModelChooserWidget(Page, **self.get_widget_options()) value = widget.get_internal_value(stub) self.assertEqual(value, str(id_))
def test_get_js_init_data(self): widget = widgets.ModelChooserWidget(Page, **self.get_widget_options()) data = widget.get_js_init_data('field-1', None, self.root_page) expected_data = { 'label': 'Page', 'required': True, 'initial_display_value': 'Welcome to your new Wagtail site!', 'display': 'title', 'list_display': [{'name': 'title', 'label': 'Title'}], 'endpoint': '/admin/modelchoosers/api/v1/model/wagtailcore.Page', 'pk_name': 'id', } self.assertEqual(data, expected_data)
def test_render_js_init(self): widget = widgets.ModelChooserWidget(Page, **self.get_widget_options()) js_init = widget.render_js_init('field-1', None, self.root_page) expected_pattern = ( r'^' # Start of line r'wagtailModelChoosers.initModelChooser\(' # Function name r'".+"' # First argument, the field id (a string) r', ' # Comma and space between arguments r'.+' # Second argument, the data (an object) r'\)' # End of function r'$' # End of line ) self.assertRegex(js_init, expected_pattern)
def test_render_html(self): widget = widgets.ModelChooserWidget(Page, **self.get_widget_options()) html = widget.render_html('test', None, {}) self.assertIn('<input type="hidden" value="" name="test" >', html)
def test_render_html_with_value(self): widget = widgets.ModelChooserWidget(Page, **self.get_widget_options()) html = widget.render_html('test', self.root_page, {}) self.assertIn('<input type="hidden" value="2" name="test" >', html)
def save(self, *args, **kwargs): self.full_clean() update_descendant_url_paths = False is_new = self.id is None if is_new: self.set_url_path(self.get_parent()) else: # update url paths if: # a) update_fields is specified and it includes any slug field # or # b) update_fields is not specified (check all slug fields in that case) slug_fields = get_translation_fields('slug') update_fields = kwargs.get('update_fields', slug_fields) updated_slug_fields = [f for f in slug_fields if f in update_fields] if updated_slug_fields: old_record = Page.objects.get(id=self.id) if any(getattr(old_record, f) != getattr(self, f) for f in updated_slug_fields): self.set_url_path(self.get_parent()) update_descendant_url_paths = True result = super(Page, self).save(*args, **kwargs) if update_descendant_url_paths: self._update_descendant_lang_url_paths(old_record) if Site.objects.filter(root_page=self).exists(): delete_root_path_cache() if is_new: cls = type(self) logger.info( "Page created: \"%s\" id=%d content_type=%s.%s path=%s", self.title, self.id, cls._meta.app_label, cls.__name__, self.url_path ) return result