本文整理汇总了Python中wagtail.core.models.Page类的典型用法代码示例。如果您正苦于以下问题:Python Page类的具体用法?Python Page怎么用?Python Page使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Page类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: get_navigation_object_from_page
def get_navigation_object_from_page(page: Page, current_page_id: int) -> dict:
page_object = {
"text": str(page.title),
"nodes": [],
"href": page.get_url(),
"state": {}
}
if isinstance(page.specific, PageWithSidebar) or isinstance(page.specific, LessonPage) or isinstance(page.specific,
ArticlePage):
menu_title = page.specific.menu_title
if not isinstance(menu_title, str):
menu_title = menu_title.decode()
if menu_title != '':
page_object["text"] = menu_title
if not page.specific.is_selectable:
page_object["selectable"] = False
if page.id == current_page_id:
page_object["state"] = {
"selected": True
}
page_object["selectable"] = False
for child in page.get_children():
if child.show_in_menus:
page_object["nodes"].append(get_navigation_object_from_page(child, current_page_id))
if len(page_object["nodes"]) == 0:
page_object.pop('nodes', None)
return page_object
开发者ID:5CORNERS,项目名称:www.le-francais.ru,代码行数:27,代码来源:views.py
示例2: test_construct_queryset_hook
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)
开发者ID:nealtodd,项目名称:wagtail,代码行数:14,代码来源:test_page_chooser.py
示例3: move_choose_destination
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)
# Pagination
paginator, child_pages = paginate(request, child_pages, per_page=50)
return render(request, 'wagtailadmin/pages/move_choose_destination.html', {
'page_to_move': page_to_move,
'viewed_page': viewed_page,
'child_pages': child_pages,
})
开发者ID:hellomrjack,项目名称:wagtail,代码行数:34,代码来源:pages.py
示例4: clean
def clean(self):
cleaned_data = super().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
开发者ID:mwharrison,项目名称:wagtail,代码行数:29,代码来源:forms.py
示例5: test_rendering
def test_rendering(root_page, example_svg_upload, dummy_wagtail_doc):
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='green', link_external='/foobar', target='_blank')
map.regions.create(element_id='blue', link_page=page, target='_top')
map.regions.create(element_id='red', link_document=dummy_wagtail_doc)
svg = map.rendered_svg
assert '/foobar' in svg
assert '_blank' in svg
assert 'nnep' in svg
assert '_top' in svg
assert ('documents/%s' % dummy_wagtail_doc.pk) in svg
开发者ID:City-of-Helsinki,项目名称:wagtail-svgmap,代码行数:18,代码来源:test_model.py
示例6: setUp
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/')
开发者ID:BertrandBordage,项目名称:wagtail,代码行数:21,代码来源:test_page_queryset.py
示例7: test_auto_recache
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
开发者ID:City-of-Helsinki,项目名称:wagtail-svgmap,代码行数:14,代码来源:test_model.py
示例8: setUpClass
def setUpClass(cls):
super().setUpClass()
cls.test_page = SimplePage(title="test", slug='test', content="test")
cls.wagtail_root = Page.get_first_root_node()
cls.wagtail_root.add_child(instance=cls.test_page)
cls.test_page_group = Group.objects.create(name="Test page")
GroupPagePermission.objects.create(
group=cls.test_page_group,
page=cls.test_page,
permission_type='edit'
)
开发者ID:BertrandBordage,项目名称:wagtail,代码行数:13,代码来源:test_site_summary.py
示例9: move_confirm
def move_confirm(request, page_to_move_id, destination_id):
page_to_move = get_object_or_404(Page, id=page_to_move_id).specific
destination = get_object_or_404(Page, id=destination_id)
if not page_to_move.permissions_for_user(request.user).can_move_to(destination):
raise PermissionDenied
if not Page._slug_is_available(page_to_move.slug, destination, page=page_to_move):
messages.error(
request,
_("The slug '{0}' is already in use at the selected parent page. Make sure the slug is unique and try again".format(page_to_move.slug))
)
return redirect('wagtailadmin_pages:move_choose_destination', page_to_move.id, destination.id)
for fn in hooks.get_hooks('before_move_page'):
result = fn(request, page_to_move, destination)
if hasattr(result, 'status_code'):
return result
if request.method == 'POST':
# any invalid moves *should* be caught by the permission check above,
# so don't bother to catch InvalidMoveToDescendant
page_to_move.move(destination, pos='last-child')
messages.success(request, _("Page '{0}' moved.").format(page_to_move.get_admin_display_title()), buttons=[
messages.button(reverse('wagtailadmin_pages:edit', args=(page_to_move.id,)), _('Edit'))
])
for fn in hooks.get_hooks('after_move_page'):
result = fn(request, page_to_move)
if hasattr(result, 'status_code'):
return result
return redirect('wagtailadmin_explore', destination.id)
return render(request, 'wagtailadmin/pages/confirm_move.html', {
'page_to_move': page_to_move,
'destination': destination,
})
开发者ID:Proper-Job,项目名称:wagtail,代码行数:38,代码来源:pages.py
示例10: get_page
def get_page(self):
(content_type_app_name, content_type_model_name,
parent_page_id) = self.args
try:
content_type = ContentType.objects.get_by_natural_key(
content_type_app_name, content_type_model_name)
except ContentType.DoesNotExist:
raise Http404
page = content_type.model_class()()
parent_page = get_object_or_404(Page, id=parent_page_id).specific
# 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
# Puts the page at the maximum possible path
# for a child of `parent_page`.
page.path = Page._get_children_path_interval(parent_page.path)[1]
return page
开发者ID:hellomrjack,项目名称:wagtail,代码行数:23,代码来源:pages.py
示例11: get_root_page
def get_root_page(self, request):
return Page.get_first_root_node()
开发者ID:BertrandBordage,项目名称:wagtail,代码行数:2,代码来源:filters.py
示例12: handle
def handle(self, *args, **options):
for node in Page.get_root_nodes():
self.set_subtree(node)
开发者ID:BertrandBordage,项目名称:wagtail,代码行数:3,代码来源:set_url_paths.py
示例13: index
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()
# This will always succeed because of the @user_passes_test above.
root_page = get_explorable_root_page(request.user)
# If this page isn't a descendant of the user's explorable root page,
# then redirect to that explorable root page instead.
if not (
parent_page.pk == root_page.pk or
parent_page.is_descendant_of(root_page)
):
return redirect('wagtailadmin_explore', root_page.pk)
parent_page = parent_page.specific
pages = parent_page.get_children().prefetch_related('content_type', 'sites_rooted_here')
# 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)
# 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 or pages.count() < 100:
# Retrieve pages in their most specific form, so that custom
# get_admin_display_title and get_url_parts methods on subclasses are respected.
# However, skip this on unpaginated listings with >100 child pages as this could
# be a significant performance hit. (This should only happen on the reorder view,
# and hopefully no-one is having to do manual reordering on listings that large...)
pages = pages.specific(defer=True)
# allow hooks to modify the queryset
for hook in hooks.get_hooks('construct_explorer_page_queryset'):
pages = hook(parent_page, pages, request)
# Pagination
if do_paginate:
paginator, pages = paginate(request, pages, per_page=50)
return render(request, 'wagtailadmin/pages/index.html', {
'parent_page': parent_page.specific,
'ordering': ordering,
'pagination_query_params': "ordering=%s" % ordering,
'pages': pages,
'do_paginate': do_paginate,
})
开发者ID:hellomrjack,项目名称:wagtail,代码行数:82,代码来源:pages.py
示例14: test_empty_queryset
def test_empty_queryset(self):
self.assertEqual(
Page.get_first_root_node(),
Page.objects.none().first_common_ancestor())
开发者ID:BertrandBordage,项目名称:wagtail,代码行数:4,代码来源:test_page_queryset.py
示例15: test_all_pages_include_self_strict
def test_all_pages_include_self_strict(self):
self.assertEqual(
Page.get_first_root_node(),
Page.objects.first_common_ancestor(include_self=True, strict=True))
开发者ID:BertrandBordage,项目名称:wagtail,代码行数:4,代码来源:test_page_queryset.py
示例16: test_all_pages
def test_all_pages(self):
self.assertEqual(
Page.get_first_root_node(),
Page.objects.first_common_ancestor())
开发者ID:BertrandBordage,项目名称:wagtail,代码行数:4,代码来源:test_page_queryset.py
示例17: handle
def handle(self, **options):
any_problems_fixed = False
for page in Page.objects.all():
try:
page.specific
except page.specific_class.DoesNotExist:
self.stdout.write("Page %d (%s) is missing a subclass record; deleting." % (page.id, page.title))
any_problems_fixed = True
page.delete()
(bad_alpha, bad_path, orphans, bad_depth, bad_numchild) = Page.find_problems()
if bad_depth:
self.stdout.write("Incorrect depth value found for pages: %s" % self.numberlist_to_string(bad_depth))
if bad_numchild:
self.stdout.write("Incorrect numchild value found for pages: %s" % self.numberlist_to_string(bad_numchild))
if bad_depth or bad_numchild:
Page.fix_tree(destructive=False)
any_problems_fixed = True
if orphans:
# The 'orphans' list as returned by treebeard only includes pages that are
# missing an immediate parent; descendants of orphans are not included.
# Deleting only the *actual* orphans is a bit silly (since it'll just create
# more orphans), so generate a queryset that contains descendants as well.
orphan_paths = Page.objects.filter(id__in=orphans).values_list('path', flat=True)
filter_conditions = []
for path in orphan_paths:
filter_conditions.append(Q(path__startswith=path))
# combine filter_conditions into a single ORed condition
final_filter = functools.reduce(operator.or_, filter_conditions)
# build a queryset of all pages to be removed; this must be a vanilla Django
# queryset rather than a treebeard MP_NodeQuerySet, so that we bypass treebeard's
# custom delete() logic that would trip up on the very same corruption that we're
# trying to fix here.
pages_to_delete = models.query.QuerySet(Page).filter(final_filter)
self.stdout.write("Orphaned pages found:")
for page in pages_to_delete:
self.stdout.write("ID %d: %s" % (page.id, page.title))
self.stdout.write('')
if options.get('interactive', True):
yes_or_no = input("Delete these pages? [y/N] ")
delete_orphans = yes_or_no.lower().startswith('y')
self.stdout.write('')
else:
# Running tests, check for the "delete_orphans" option
delete_orphans = options.get('delete_orphans', False)
if delete_orphans:
deletion_count = len(pages_to_delete)
pages_to_delete.delete()
self.stdout.write(
"%d orphaned page%s deleted." % (deletion_count, "s" if deletion_count != 1 else "")
)
any_problems_fixed = True
if any_problems_fixed:
# re-run find_problems to see if any new ones have surfaced
(bad_alpha, bad_path, orphans, bad_depth, bad_numchild) = Page.find_problems()
if any((bad_alpha, bad_path, orphans, bad_depth, bad_numchild)):
self.stdout.write("Remaining problems (cannot fix automatically):")
if bad_alpha:
self.stdout.write(
"Invalid characters found in path for pages: %s" % self.numberlist_to_string(bad_alpha)
)
if bad_path:
self.stdout.write("Invalid path length found for pages: %s" % self.numberlist_to_string(bad_path))
if orphans:
self.stdout.write("Orphaned pages found: %s" % self.numberlist_to_string(orphans))
if bad_depth:
self.stdout.write("Incorrect depth value found for pages: %s" % self.numberlist_to_string(bad_depth))
if bad_numchild:
self.stdout.write(
"Incorrect numchild value found for pages: %s" % self.numberlist_to_string(bad_numchild)
)
elif any_problems_fixed:
self.stdout.write("All problems fixed.")
else:
self.stdout.write("No problems found.")
开发者ID:morris-tech,项目名称:wagtail,代码行数:87,代码来源:fixtree.py
示例18: browse
def browse(request, parent_page_id=None):
# 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'
user_perm = request.GET.get('user_perms', False)
try:
desired_classes = page_models_from_string(page_type_string)
except (ValueError, LookupError):
raise Http404
# Find parent page
if parent_page_id:
parent_page = get_object_or_404(Page, id=parent_page_id)
elif desired_classes == (Page,):
# Just use the root page
parent_page = Page.get_first_root_node()
else:
# Find the highest common ancestor for the specific classes passed in
# In many cases, such as selecting an EventPage under an EventIndex,
# this will help the administrator find their page quicker.
all_desired_pages = filter_page_type(Page.objects.all(), desired_classes)
parent_page = all_desired_pages.first_common_ancestor()
# Get children of parent page
pages = parent_page.get_children().specific()
# allow hooks to modify the queryset
for hook in hooks.get_hooks('construct_page_chooser_queryset'):
pages = hook(pages, request)
# Filter them by page type
if desired_classes != (Page,):
# 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
can_choose_root = request.GET.get('can_choose_root', False)
# Do permission lookups for this user now, instead of for every page.
permission_proxy = UserPagePermissionsProxy(request.user)
# Parent page can be chosen if it is a instance of desired_classes
parent_page.can_choose = can_choose_page(
parent_page, permission_proxy, desired_classes, can_choose_root, user_perm)
# 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:
page.can_choose = can_choose_page(page, permission_proxy, desired_classes, can_choose_root, user_perm)
page.can_descend = page.get_children_count()
# Render
context = shared_context(request, {
'parent_page': parent_page,
'parent_page_id': parent_page.pk,
'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')
})
return render_modal_workflow(
request,
'wagtailadmin/chooser/browse.html', None,
context,
json_data={'step': 'browse', 'parent_page_id': context['parent_page_id']},
)
开发者ID:BertrandBordage,项目名称:wagtail,代码行数:76,代码来源:chooser.py
示例19: normal_page
def normal_page(self, request):
return Page.serve(self, request)
开发者ID:chrisdev,项目名称:wagtail-cookiecutter-foundation,代码行数:2,代码来源:models.py
示例20: index
def index(request, parent_page_id=None):
if parent_page_id:
parent_page = get_object_or_404(Page, id=parent_page_id).specific
else:
parent_page = Page.get_first_root_node().specific
pages = parent_page.get_children().prefetch_related('content_type', 'sites_rooted_here')
# 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)
# 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:
# Retrieve pages in their most specific form.
# Only do this for paginated listings, as this could potentially be a
# very expensive operation when performed on a large queryset.
pages = pages.specific()
# allow hooks to modify the queryset
for hook in hooks.get_hooks('construct_explorer_page_queryset'):
pages = hook(parent_page, pages, request)
# Pagination
if do_paginate:
paginator, pages = paginate(request, pages, per_page=50)
return render(request, 'wagtailadmin/pages/index.html', {
'parent_page': parent_page.specific,
'ordering': ordering,
'pagination_query_params': "ordering=%s" % ordering,
'pages': pages,
'do_paginate': do_paginate,
})
开发者ID:springload,项目名称:wagtail,代码行数:67,代码来源:pages.py
注:本文中的wagtail.core.models.Page类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论