response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Returns the preferred display name for the given user object: the result of user.get_full_name() if implemented and non-empty, or user.get_username() otherwise.
def get_user_display_name(user): """ Returns the preferred display name for the given user object: the result of user.get_full_name() if implemented and non-empty, or user.get_username() otherwise. """ try: full_name = user.get_full_name().strip() if full_name: return full_name except AttributeError: pass try: return user.get_username() except AttributeError: # we were passed None or something else that isn't a valid user object; return # empty string to replicate the behaviour of {{ user.get_full_name|default:user.get_username }} return ""
Given a URL and a dictionary of query parameters, returns a new URL with those query parameters added or updated. If the value of a query parameter is None, that parameter will be removed from the URL.
def set_query_params(url: str, params: dict): """ Given a URL and a dictionary of query parameters, returns a new URL with those query parameters added or updated. If the value of a query parameter is None, that parameter will be removed from the URL. """ scheme, netloc, path, query, fragment = urlsplit(url) querydict = parse_qs(query) querydict.update(params) querydict = {key: value for key, value in querydict.items() if value is not None} query = urlencode(querydict, doseq=True) return urlunsplit((scheme, netloc, path, query, fragment))
Triggers the keyboard shortcuts dialog to open when clicked while preventing the default link click action.
def register_keyboard_shortcuts_menu_item(): """ Triggers the keyboard shortcuts dialog to open when clicked while preventing the default link click action. """ return MenuItem( _("Shortcuts"), icon_name="keyboard", order=1200, attrs={ "role": "button", # Ensure screen readers announce this as a button "data-a11y-dialog-show": "keyboard-shortcuts-dialog", "data-action": "w-action#noop:prevent:stop", "data-controller": "w-action", }, name="keyboard-shortcuts-trigger", url="#", )
Define parameters for form fields to be used by WagtailAdminModelForm for a given database field.
def register_form_field_override( db_field_class, to=None, override=None, exact_class=False ): """ Define parameters for form fields to be used by WagtailAdminModelForm for a given database field. """ if override is None: raise ImproperlyConfigured( "register_form_field_override must be passed an 'override' keyword argument" ) if to and db_field_class != models.ForeignKey: raise ImproperlyConfigured( "The 'to' argument on register_form_field_override is only valid for ForeignKey fields" ) registry.register(db_field_class, to=to, value=override, exact_class=exact_class)
Generates a form class for the given task model. If the form is to edit an existing task, set for_edit to True. This applies the readonly restrictions on fields defined in admin_form_readonly_on_edit_fields.
def get_task_form_class(task_model, for_edit=False): """ Generates a form class for the given task model. If the form is to edit an existing task, set for_edit to True. This applies the readonly restrictions on fields defined in admin_form_readonly_on_edit_fields. """ fields = task_model.admin_form_fields form_class = forms.modelform_factory( task_model, form=BaseTaskForm, fields=fields, widgets=getattr(task_model, "admin_form_widgets", {}), ) if for_edit: for field_name in getattr(task_model, "admin_form_readonly_on_edit_fields", []): if field_name not in form_class.base_fields: raise ImproperlyConfigured( "`%s.admin_form_readonly_on_edit_fields` contains the field " "'%s' that doesn't exist. Did you forget to add " "it to `%s.admin_form_fields`?" % (task_model.__name__, field_name, task_model.__name__) ) form_class.base_fields[field_name].disabled = True return form_class
Returns an edit handler which provides the "name" and "tasks" fields for workflow.
def get_workflow_edit_handler(): """ Returns an edit handler which provides the "name" and "tasks" fields for workflow. """ # Note. It's a bit of a hack that we use edit handlers here. Ideally, it should be # made easier to reuse the inline panel templates for any formset. # Since this form is internal, we're OK with this for now. We might want to revisit # this decision later if we decide to allow custom fields on Workflows. panels = [ FieldPanel("name", heading=_("Give your workflow a name")), InlinePanel( "workflow_tasks", [ FieldPanel("task", widget=AdminTaskChooser(show_clear_link=False)), ], heading=_("Add tasks to your workflow"), label=_("Task"), icon="thumbtack", ), ] edit_handler = ObjectList(panels, base_form_class=WagtailAdminModelForm) return edit_handler.bind_to_model(Workflow)
Reverse the above additions of permissions.
def remove_admin_access_permissions(apps, schema_editor): """Reverse the above additions of permissions.""" ContentType = apps.get_model("contenttypes.ContentType") Permission = apps.get_model("auth.Permission") wagtailadmin_content_type = ContentType.objects.get( app_label="wagtailadmin", model="admin", ) # This cascades to Group Permission.objects.filter( content_type=wagtailadmin_content_type, codename="access_admin", ).delete()
Construct a ModelForm subclass using the given model and base form class. Any additional keyword arguments are used to populate the form's Meta class.
def get_form_for_model( model, form_class=WagtailAdminModelForm, **kwargs, ): """ Construct a ModelForm subclass using the given model and base form class. Any additional keyword arguments are used to populate the form's Meta class. """ # This is really just Django's modelform_factory, tweaked to accept arbitrary kwargs. meta_class_attrs = kwargs meta_class_attrs["model"] = model # The kwargs passed here are expected to come from Panel.get_form_options, which collects # them by descending the tree of child edit handlers. If there are no edit handlers that # specify form fields, this can legitimately result in both 'fields' and 'exclude' being # absent, which ModelForm doesn't normally allow. In this case, explicitly set fields to []. if "fields" not in meta_class_attrs and "exclude" not in meta_class_attrs: meta_class_attrs["fields"] = [] # Give this new form class a reasonable name. class_name = model.__name__ + "Form" bases = (form_class.Meta,) if hasattr(form_class, "Meta") else () Meta = type("Meta", bases, meta_class_attrs) form_class_attrs = {"Meta": Meta} metaclass = type(form_class) bases = [form_class] if issubclass(model, DraftStateMixin): bases.insert(0, WagtailAdminDraftStateFormMixin) return metaclass(class_name, tuple(bases), form_class_attrs)
Get the panel to use in the Wagtail admin when editing this model.
def get_edit_handler(model): """ Get the panel to use in the Wagtail admin when editing this model. """ if hasattr(model, "edit_handler"): # use the edit handler specified on the model class panel = model.edit_handler else: panels = extract_panel_definitions_from_model_class(model) panel = ObjectList(panels) return panel.bind_to_model(model)
Get the panel to use in the Wagtail admin when editing this page type.
def _get_page_edit_handler(cls): """ Get the panel to use in the Wagtail admin when editing this page type. """ if hasattr(cls, "edit_handler"): edit_handler = cls.edit_handler else: # construct a TabbedInterface made up of content_panels, promote_panels # and settings_panels, skipping any which are empty tabs = [] if cls.content_panels: tabs.append(ObjectList(cls.content_panels, heading=gettext_lazy("Content"))) if cls.promote_panels: tabs.append(ObjectList(cls.promote_panels, heading=gettext_lazy("Promote"))) if cls.settings_panels: tabs.append( ObjectList(cls.settings_panels, heading=gettext_lazy("Settings")) ) edit_handler = TabbedInterface(tabs, base_form_class=cls.base_form_class) return edit_handler.bind_to_model(cls)
Clear page edit handler cache when global WAGTAILADMIN_COMMENTS_ENABLED settings are changed
def reset_edit_handler_cache(**kwargs): """ Clear page edit handler cache when global WAGTAILADMIN_COMMENTS_ENABLED settings are changed """ if kwargs["setting"] == "WAGTAILADMIN_COMMENTS_ENABLED": set_default_page_edit_handlers(Page) for model in apps.get_models(): if issubclass(model, Page): model.get_edit_handler.cache_clear() get_edit_handler.cache_clear()
<a linktype="page" id="1">internal page link</a>
def link_entity(props): """ <a linktype="page" id="1">internal page link</a> """ id_ = props.get("id") link_props = {} if id_ is not None: link_props["linktype"] = "page" link_props["id"] = id_ else: link_props["href"] = check_url(props.get("url")) return DOM.create_element("a", link_props, props["children"])
Utility function for adding an unstyled (paragraph) block to contentstate; useful for element handlers that aren't paragraph elements themselves, but need to insert paragraphs to ensure correctness
def add_paragraph_block(state, contentstate): """ Utility function for adding an unstyled (paragraph) block to contentstate; useful for element handlers that aren't paragraph elements themselves, but need to insert paragraphs to ensure correctness """ block = Block("unstyled", depth=state.list_depth) contentstate.blocks.append(block) state.current_block = block state.leading_whitespace = STRIP_WHITESPACE state.has_preceding_nonatomic_block = True
Usage: {% page_permissions page as page_perms %} Sets the variable 'page_perms' to a PagePermissionTester object that can be queried to find out what actions the current logged-in user can perform on the given page.
def page_permissions(context, page): """ Usage: {% page_permissions page as page_perms %} Sets the variable 'page_perms' to a PagePermissionTester object that can be queried to find out what actions the current logged-in user can perform on the given page. """ return page.permissions_for_user(context["request"].user)
Usage: {% is_page obj as is_page %} Sets the variable 'is_page' to True if the given object is a Page instance, False otherwise. Useful in shared templates that accept both Page and non-Page objects (e.g. snippets with the optional features enabled).
def is_page(obj): """ Usage: {% is_page obj as is_page %} Sets the variable 'is_page' to True if the given object is a Page instance, False otherwise. Useful in shared templates that accept both Page and non-Page objects (e.g. snippets with the optional features enabled). """ return isinstance(obj, Page)
Usage: {% admin_edit_url obj user %} Returns the URL of the edit view for the given object and user using the registered AdminURLFinder for the object. The AdminURLFinder instance is cached in the context for the duration of the page request. The user argument is optional and defaults to request.user if request is available in the context.
def admin_edit_url(context, obj, user=None): """ Usage: {% admin_edit_url obj user %} Returns the URL of the edit view for the given object and user using the registered AdminURLFinder for the object. The AdminURLFinder instance is cached in the context for the duration of the page request. The user argument is optional and defaults to request.user if request is available in the context. """ if not user and "request" in context: user = context["request"].user if "admin_url_finder" not in context: context["admin_url_finder"] = AdminURLFinder(user) return context["admin_url_finder"].get_edit_url(obj)
Usage: {% admin_url_name obj action %} Returns the URL name of the given action for the given object, e.g. 'wagtailadmin_pages:edit' for a Page object and 'edit' action. Works with pages and snippets only.
def admin_url_name(obj, action): """ Usage: {% admin_url_name obj action %} Returns the URL name of the given action for the given object, e.g. 'wagtailadmin_pages:edit' for a Page object and 'edit' action. Works with pages and snippets only. """ if isinstance(obj, Page): return f"wagtailadmin_pages:{action}" return obj.snippet_viewset.get_url_name(action)
Usage: {% latest_str obj %} Returns the latest string representation of an object, making use of the latest revision where available to reflect draft changes.
def latest_str(obj): """ Usage: {% latest_str obj %} Returns the latest string representation of an object, making use of the latest revision where available to reflect draft changes. """ return get_latest_str(obj)
Usage <div class="{% classnames "w-base" classname active|yesno:"w-base--active," any_other_var %}"></div> Returns any args as a space-separated joined string for using in HTML class names.
def classnames(*classes): """ Usage <div class="{% classnames "w-base" classname active|yesno:"w-base--active," any_other_var %}"></div> Returns any args as a space-separated joined string for using in HTML class names. """ flattened = [] for classname in classes: if isinstance(classname, str): flattened.append(classname) elif hasattr(classname, "__iter__"): flattened.extend(classname) return " ".join([classname.strip() for classname in flattened if classname])
Usage: {% test_collection_is_public collection as is_public %} Sets 'is_public' to True iff there are no collection view restrictions in place on this collection. Caches the list of collection view restrictions in the context, to avoid repeated DB queries on repeated calls.
def test_collection_is_public(context, collection): """ Usage: {% test_collection_is_public collection as is_public %} Sets 'is_public' to True iff there are no collection view restrictions in place on this collection. Caches the list of collection view restrictions in the context, to avoid repeated DB queries on repeated calls. """ if "all_collection_view_restrictions" not in context: context[ "all_collection_view_restrictions" ] = CollectionViewRestriction.objects.select_related("collection").values_list( "collection__name", flat=True ) is_private = collection.name in context["all_collection_view_restrictions"] return not is_private
Usage: {% test_page_is_public page as is_public %} Sets 'is_public' to True iff there are no page view restrictions in place on this page. Caches the list of page view restrictions on the request, to avoid repeated DB queries on repeated calls.
def test_page_is_public(context, page): """ Usage: {% test_page_is_public page as is_public %} Sets 'is_public' to True iff there are no page view restrictions in place on this page. Caches the list of page view restrictions on the request, to avoid repeated DB queries on repeated calls. """ if not hasattr(context["request"], "all_page_view_restriction_paths"): context[ "request" ].all_page_view_restriction_paths = PageViewRestriction.objects.select_related( "page" ).values_list("page__path", flat=True) is_private = any( page.path.startswith(restricted_path) for restricted_path in context["request"].all_page_view_restriction_paths ) return not is_private
Example: {% hook_output 'insert_global_admin_css' %} Whenever we have a hook whose functions take no parameters and return a string, this tag can be used to output the concatenation of all of those return values onto the page. Note that the output is not escaped - it is the hook function's responsibility to escape unsafe content.
def hook_output(hook_name): """ Example: {% hook_output 'insert_global_admin_css' %} Whenever we have a hook whose functions take no parameters and return a string, this tag can be used to output the concatenation of all of those return values onto the page. Note that the output is not escaped - it is the hook function's responsibility to escape unsafe content. """ snippets = [fn() for fn in hooks.get_hooks(hook_name)] return mark_safe("".join(snippets))
Usage: {{ field|render_with_errors }} as opposed to {{ field }}. If the field (a BoundField instance) has errors on it, and the associated widget implements a render_with_errors method, call that; otherwise, call the regular widget rendering mechanism.
def render_with_errors(bound_field): """ Usage: {{ field|render_with_errors }} as opposed to {{ field }}. If the field (a BoundField instance) has errors on it, and the associated widget implements a render_with_errors method, call that; otherwise, call the regular widget rendering mechanism. """ widget = bound_field.field.widget if bound_field.errors and hasattr(widget, "render_with_errors"): return widget.render_with_errors( bound_field.html_name, bound_field.value(), attrs={"id": bound_field.auto_id}, errors=bound_field.errors, ) else: attrs = {} # If the widget doesn't have an aria-describedby attribute, # and the field has help text, and the field has an id, # add an aria-describedby attribute pointing to the help text. # In this case, the corresponding help text element's id is set in the # wagtailadmin/shared/field.html template. # In Django 5.0 and up, this is done automatically, but we want to keep # this code because we use a different convention for the help text id # (we use -helptext suffix instead of Django's _helptext). if ( not bound_field.field.widget.attrs.get("aria-describedby") and bound_field.field.help_text and bound_field.id_for_label ): attrs["aria-describedby"] = f"{bound_field.id_for_label}-helptext" return bound_field.as_widget(attrs=attrs)
Return true if this field has errors that were not accounted for by render_with_errors, because the widget does not support the render_with_errors method
def has_unrendered_errors(bound_field): """ Return true if this field has errors that were not accounted for by render_with_errors, because the widget does not support the render_with_errors method """ return bound_field.errors and not hasattr( bound_field.field.widget, "render_with_errors" )
Print out the current querystring. Any keyword arguments to this template tag will be added to the querystring before it is printed out. <a href="/page/{% querystring key='value' %}"> Will result in something like: <a href="/page/?foo=bar&key=value">
def querystring(context, **kwargs): """ Print out the current querystring. Any keyword arguments to this template tag will be added to the querystring before it is printed out. <a href="/page/{% querystring key='value' %}"> Will result in something like: <a href="/page/?foo=bar&key=value"> """ request = context["request"] querydict = request.GET.copy() # Can't do querydict.update(kwargs), because QueryDict.update() appends to # the list of values, instead of replacing the values. for key, value in kwargs.items(): if value is None: # Remove the key if the value is None querydict.pop(key, None) else: # Set the key otherwise querydict[key] = str(value) return "?" + querydict.urlencode()
Print out a querystring with an updated page number: {% if page.has_next_page %} <a href="{% pagination_link page.next_page_number %}">Next page</a> {% endif %}
def pagination_querystring(context, page_number, page_key="p"): """ Print out a querystring with an updated page number: {% if page.has_next_page %} <a href="{% pagination_link page.next_page_number %}">Next page</a> {% endif %} """ return querystring(context, **{page_key: page_number})
Print pagination previous/next links, and the page count. Take the following arguments: page The current page of results. This should be a Django pagination `Page` instance base_url The base URL of the next/previous page, with no querystring. This is optional, and defaults to the current page by just printing the querystring for the next/previous page. page_key The name of the page variable in the query string. Defaults to 'p'. classname Extra classes to add to the next/previous links.
def paginate(context, page, base_url="", page_key="p", classname=""): """ Print pagination previous/next links, and the page count. Take the following arguments: page The current page of results. This should be a Django pagination `Page` instance base_url The base URL of the next/previous page, with no querystring. This is optional, and defaults to the current page by just printing the querystring for the next/previous page. page_key The name of the page variable in the query string. Defaults to 'p'. classname Extra classes to add to the next/previous links. """ request = context["request"] return { "base_url": base_url, "classname": classname, "request": request, "page": page, "page_key": page_key, "paginator": page.paginator, }
Displays a user avatar using the avatar template Usage: {% load wagtailadmin_tags %} ... {% avatar user=request.user size='small' tooltip='JaneDoe' %} :param user: the user to get avatar information from (User) :param size: default None (None|'small'|'large'|'square') :param tooltip: Optional tooltip to display under the avatar (string) :return: Rendered template snippet
def avatar(user=None, classname=None, size=None, tooltip=None): """ Displays a user avatar using the avatar template Usage: {% load wagtailadmin_tags %} ... {% avatar user=request.user size='small' tooltip='JaneDoe' %} :param user: the user to get avatar information from (User) :param size: default None (None|'small'|'large'|'square') :param tooltip: Optional tooltip to display under the avatar (string) :return: Rendered template snippet """ return {"user": user, "classname": classname, "size": size, "tooltip": tooltip}
Return the tag for this message's level as defined in django.contrib.messages.constants.DEFAULT_TAGS, ignoring the project-level MESSAGE_TAGS setting (which end-users might customise).
def message_level_tag(message): """ Return the tag for this message's level as defined in django.contrib.messages.constants.DEFAULT_TAGS, ignoring the project-level MESSAGE_TAGS setting (which end-users might customise). """ return MESSAGE_TAGS.get(message.level)
A template tag that receives a user and size and return the appropriate avatar url for that user. Example usage: {% avatar_url request.user 50 %}
def avatar_url(user, size=50, gravatar_only=False): """ A template tag that receives a user and size and return the appropriate avatar url for that user. Example usage: {% avatar_url request.user 50 %} """ if ( not gravatar_only and hasattr(user, "wagtail_userprofile") and user.wagtail_userprofile.avatar ): return user.wagtail_userprofile.avatar.url if hasattr(user, "email"): gravatar_url = get_gravatar_url(user.email, size=size) if gravatar_url is not None: return gravatar_url return versioned_static_func("wagtailadmin/images/default-user-avatar.png")
Retrieves the theme name for the current user.
def admin_theme_classname(context): """ Retrieves the theme name for the current user. """ user = context["request"].user theme_name = ( user.wagtail_userprofile.theme if hasattr(user, "wagtail_userprofile") else "system" ) density_name = ( user.wagtail_userprofile.density if hasattr(user, "wagtail_userprofile") else "default" ) return f"w-theme-{theme_name} w-density-{density_name}"
Variant of the {% static %}` tag for use in notification emails - tries to form a full URL using WAGTAILADMIN_BASE_URL if the static URL isn't already a full URL.
def notification_static(path): """ Variant of the {% static %}` tag for use in notification emails - tries to form a full URL using WAGTAILADMIN_BASE_URL if the static URL isn't already a full URL. """ return urljoin(base_url_setting(), static(path))
Wrapper for Django's static file finder to append a cache-busting query parameter that updates on each Wagtail version
def versioned_static(path): """ Wrapper for Django's static file finder to append a cache-busting query parameter that updates on each Wagtail version """ return versioned_static_func(path)
Abstracts away the actual icon implementation. Usage: {% load wagtailadmin_tags %} ... {% icon name="cogs" classname="icon--red" title="Settings" %} :param name: the icon name/id, required (string) :param classname: defaults to 'icon' if not provided (string) :param title: accessible label intended for screen readers (string) :return: Rendered template snippet (string)
def icon(name=None, classname=None, title=None, wrapped=False): """ Abstracts away the actual icon implementation. Usage: {% load wagtailadmin_tags %} ... {% icon name="cogs" classname="icon--red" title="Settings" %} :param name: the icon name/id, required (string) :param classname: defaults to 'icon' if not provided (string) :param title: accessible label intended for screen readers (string) :return: Rendered template snippet (string) """ if not name: raise ValueError("You must supply an icon name") return { "name": name, "classname": classname or "icon", "title": title, "wrapped": wrapped, }
Generates a status-tag css with <span></span> or <a><a/> implementation. Usage: {% status label="live" url="/test/" title="title" hidden_label="current status:" classname="w-status--primary" %} :param label: the status test, (string) :param classname: defaults to 'status-tag' if not provided (string) :param url: the status url(to specify the use of anchor tag instead of default span), (string) :param title: accessible label intended for screen readers (string) :param hidden_label : the to specify the additional visually hidden span text, (string) :param attrs: any additional HTML attributes (as a string) to append to the root element :return: Rendered template snippet (string)
def status( label=None, classname=None, url=None, title=None, hidden_label=None, attrs=None, ): """ Generates a status-tag css with <span></span> or <a><a/> implementation. Usage: {% status label="live" url="/test/" title="title" hidden_label="current status:" classname="w-status--primary" %} :param label: the status test, (string) :param classname: defaults to 'status-tag' if not provided (string) :param url: the status url(to specify the use of anchor tag instead of default span), (string) :param title: accessible label intended for screen readers (string) :param hidden_label : the to specify the additional visually hidden span text, (string) :param attrs: any additional HTML attributes (as a string) to append to the root element :return: Rendered template snippet (string) """ return { "label": label, "attrs": attrs, "classname": classname, "hidden_label": hidden_label, "title": title, "url": url, }
Returns a simplified timesince: 19 hours, 48 minutes ago -> 19 hours ago 1 week, 1 day ago -> 1 week ago 0 minutes ago -> just now
def timesince_simple(d): """ Returns a simplified timesince: 19 hours, 48 minutes ago -> 19 hours ago 1 week, 1 day ago -> 1 week ago 0 minutes ago -> just now """ time_period = timesince(d).split(",")[0] if time_period == avoid_wrapping(_("0 minutes")): return _("just now") return _("%(time_period)s ago") % {"time_period": time_period}
Returns: - the time of update if last_update is today, if show_time_prefix=True, the output will be prefixed with "at " - time since last update otherwise. Defaults to the simplified timesince, but can return the full string if needed
def timesince_last_update( last_update, show_time_prefix=False, user_display_name="", use_shorthand=True ): """ Returns: - the time of update if last_update is today, if show_time_prefix=True, the output will be prefixed with "at " - time since last update otherwise. Defaults to the simplified timesince, but can return the full string if needed """ # translation usage below is intentionally verbose to be easier to work with translations current_datetime = timezone.now() if timezone.is_aware(current_datetime): # timezone support is enabled - make last_update timezone-aware and set to the user's # timezone current_datetime = timezone.localtime(current_datetime) if timezone.is_aware(last_update): local_datetime = timezone.localtime(last_update) else: local_datetime = timezone.make_aware(last_update) else: # timezone support is disabled - use naive datetimes if timezone.is_aware(last_update): local_datetime = timezone.make_naive(last_update) else: local_datetime = last_update # Use an explicit timestamp if last_update is today as seen in the current user's time zone if local_datetime.date() == current_datetime.date(): time_str = local_datetime.strftime("%H:%M") if show_time_prefix: if user_display_name: return _("at %(time)s by %(user_display_name)s") % { "time": time_str, "user_display_name": user_display_name, } else: return _("at %(time)s") % {"time": time_str} else: if user_display_name: return _("%(time)s by %(user_display_name)s") % { "time": time_str, "user_display_name": user_display_name, } else: return time_str else: if use_shorthand: time_period = timesince(local_datetime, now=current_datetime).split(",")[0] else: time_period = timesince(local_datetime, now=current_datetime) if user_display_name: return _("%(time_period)s ago by %(user_display_name)s") % { "time_period": time_period, "user_display_name": user_display_name, } else: return _("%(time_period)s ago") % {"time_period": time_period}
Returns the Locale display name given its id.
def locale_label_from_id(locale_id): """ Returns the Locale display name given its id. """ return get_locales_display_names().get(locale_id)
Store a template fragment as a variable. Usage: {% fragment as header_title %} {% blocktrans trimmed %}Welcome to the {{ site_name }} Wagtail CMS{% endblocktrans %} {% endfragment %} Copy-paste of slippers’ fragment template tag. See https://github.com/mixxorz/slippers/blob/254c720e6bb02eb46ae07d104863fce41d4d3164/slippers/templatetags/slippers.py#L173. To strip leading and trailing whitespace produced in the fragment, use the `stripped` option. This is useful if you need to check if the resulting fragment is empty (after leading and trailing spaces are removed): {% fragment stripped as recipient %} {{ title }} {{ first_name }} {{ last_name }} {% endfragment } {% if recipient %} Recipient: {{ recipient }} {% endif %} Note that the stripped option only strips leading and trailing spaces, unlike {% blocktrans trimmed %} that also does line-by-line stripping. This is because the fragment may contain HTML tags that are sensitive to whitespace, such as <pre> and <code>.
def fragment(parser, token): """ Store a template fragment as a variable. Usage: {% fragment as header_title %} {% blocktrans trimmed %}Welcome to the {{ site_name }} Wagtail CMS{% endblocktrans %} {% endfragment %} Copy-paste of slippers’ fragment template tag. See https://github.com/mixxorz/slippers/blob/254c720e6bb02eb46ae07d104863fce41d4d3164/slippers/templatetags/slippers.py#L173. To strip leading and trailing whitespace produced in the fragment, use the `stripped` option. This is useful if you need to check if the resulting fragment is empty (after leading and trailing spaces are removed): {% fragment stripped as recipient %} {{ title }} {{ first_name }} {{ last_name }} {% endfragment } {% if recipient %} Recipient: {{ recipient }} {% endif %} Note that the stripped option only strips leading and trailing spaces, unlike {% blocktrans trimmed %} that also does line-by-line stripping. This is because the fragment may contain HTML tags that are sensitive to whitespace, such as <pre> and <code>. """ error_message = "The syntax for fragment is {% fragment as variable_name %}" try: tag_name, *options, target_var = token.split_contents() nodelist = parser.parse(("endfragment",)) parser.delete_first_token() except ValueError: if settings.DEBUG: raise template.TemplateSyntaxError(error_message) return "" stripped = "stripped" in options return FragmentNode(nodelist, target_var, stripped=stripped)
Renders a form field in standard Wagtail admin layout. - `field` - The Django form field to render. - `rendered_field` - The rendered HTML of the field, to be used in preference to `field`. - `classname` - For legacy patterns requiring field-specific classes. Avoid if possible. - `show_label` - Hide the label if it is rendered outside of the field. - `id_for_label` - Manually set this this if the field’s HTML isn’t rendered by Django (for example hard-coded in HTML). We add an id to the label so we can use it as a descriptor for the "Add comment" button. - `sr_only_label` - Make the label invisible for all but screen reader users. Use this if the field is displayed without a label. - `icon` - Some fields have an icon, though this is generally a legacy pattern. - `help_text` - Manually set this if the field’s HTML is hard-coded. - `help_text_id` - The help text’s id, necessary so it can be attached to the field with `aria-describedby`. - `show_add_comment_button` - Display a comment control within Wagtail forms. - `label_text` - Manually set this if the field’s HTML is hard-coded. - `error_message_id` - ID of the error message container element.
def formattedfield( field=None, rendered_field=None, classname="", show_label=True, id_for_label=None, sr_only_label=False, icon=None, help_text=None, help_text_id=None, show_add_comment_button=False, label_text=None, error_message_id=None, ): """ Renders a form field in standard Wagtail admin layout. - `field` - The Django form field to render. - `rendered_field` - The rendered HTML of the field, to be used in preference to `field`. - `classname` - For legacy patterns requiring field-specific classes. Avoid if possible. - `show_label` - Hide the label if it is rendered outside of the field. - `id_for_label` - Manually set this this if the field’s HTML isn’t rendered by Django (for example hard-coded in HTML). We add an id to the label so we can use it as a descriptor for the "Add comment" button. - `sr_only_label` - Make the label invisible for all but screen reader users. Use this if the field is displayed without a label. - `icon` - Some fields have an icon, though this is generally a legacy pattern. - `help_text` - Manually set this if the field’s HTML is hard-coded. - `help_text_id` - The help text’s id, necessary so it can be attached to the field with `aria-describedby`. - `show_add_comment_button` - Display a comment control within Wagtail forms. - `label_text` - Manually set this if the field’s HTML is hard-coded. - `error_message_id` - ID of the error message container element. """ label_for = id_for_label or (field and field.id_for_label) or "" context = { "classname": classname, "show_label": show_label, "sr_only_label": sr_only_label, "icon": icon, "show_add_comment_button": show_add_comment_button, "error_message_id": error_message_id, "label_for": label_for, "label_id": f"{label_for}-label" if label_for else "", "label_text": label_text or (field and field.label) or "", "required": field and field.field.required, "contentpath": field.name if field else "", "help_text": help_text or (field and field.help_text) or "", } if help_text_id: context["help_text_id"] = help_text_id elif field and field.help_text and field.id_for_label: context["help_text_id"] = f"{field.id_for_label}-helptext" else: context["help_text_id"] = "" if field: context["rendered_field"] = rendered_field or render_with_errors(field) context[ "field_classname" ] = f"w-field--{ fieldtype(field) } w-field--{ widgettype(field) }" errors = field.errors has_errors = bool(errors) if has_errors and hasattr(field.field.widget, "render_with_errors"): # field handles its own error rendering, so don't output them here # (but still keep has_errors=True to keep the error styling) errors = [] context["has_errors"] = has_errors context["errors"] = errors else: context["rendered_field"] = rendered_field context["field_classname"] = "" context["has_errors"] = False context["errors"] = [] return context
Variant of formattedfield that takes its arguments from the template context. Used by the wagtailadmin/shared/field.html template.
def formattedfieldfromcontext(context): """ Variant of formattedfield that takes its arguments from the template context. Used by the wagtailadmin/shared/field.html template. """ kwargs = {} for arg in ( "field", "rendered_field", "classname", "show_label", "id_for_label", "sr_only_label", "icon", "help_text", "help_text_id", "show_add_comment_button", "label_text", "error_message_id", ): if arg in context: kwargs[arg] = context[arg] return formattedfield(**kwargs)
Renders the keyboard shortcuts dialog content with the appropriate shortcuts for the user's platform. Note: Shortcut keys are intentionally not translated.
def keyboard_shortcuts_dialog(context): """ Renders the keyboard shortcuts dialog content with the appropriate shortcuts for the user's platform. Note: Shortcut keys are intentionally not translated. """ user_agent = context["request"].headers.get("User-Agent", "") is_mac = re.search(r"Mac|iPod|iPhone|iPad", user_agent) modifier = "⌘" if is_mac else "Ctrl" return { "shortcuts": { ("actions-common", _("Common actions")): [ (_("Copy"), f"{modifier} + c"), (_("Cut"), f"{modifier} + x"), (_("Paste"), f"{modifier} + v"), ( _("Paste and match style") if is_mac else _("Paste without formatting"), f"{modifier} + Shift + v", ), (_("Undo"), f"{modifier} + z"), ( _("Redo"), f"{modifier} + Shift + z" if is_mac else f"{modifier} + y", ), ], ("actions-model", _("Actions")): [ (_("Save changes"), f"{modifier} + s"), (_("Preview"), f"{modifier} + p"), ], ("rich-text-content", _("Text content")): [ (_("Insert or edit a link"), f"{modifier} + k") ], ("rich-text-formatting", _("Text formatting")): [ (_("Bold"), f"{modifier} + b"), (_("Italic"), f"{modifier} + i"), (_("Underline"), f"{modifier} + u"), (_("Monospace (code)"), f"{modifier} + j"), (_("Strike-through"), f"{modifier} + x"), (_("Superscript"), f"{modifier} + ."), (_("Subscript"), f"{modifier} + ,"), ], } }
Given a template context, try and find a Page variable in the common places. Returns None if a page can not be found.
def get_page_instance(context): """ Given a template context, try and find a Page variable in the common places. Returns None if a page can not be found. """ possible_names = [PAGE_TEMPLATE_VAR, "self"] for name in possible_names: if name in context: page = context[name] if isinstance(page, Page): return page
Test whether two contentState structures are equal, ignoring 'key' properties if match_keys=False
def content_state_equal(v1, v2, match_keys=False): "Test whether two contentState structures are equal, ignoring 'key' properties if match_keys=False" if type(v1) != type(v2): return False if isinstance(v1, dict): if set(v1.keys()) != set(v2.keys()): return False return all( (k == "key" and not match_keys) or content_state_equal(v, v2[k], match_keys=match_keys) for k, v in v1.items() ) elif isinstance(v1, list): if len(v1) != len(v2): return False return all( content_state_equal(a, b, match_keys=match_keys) for a, b in zip(v1, v2) ) else: return v1 == v2
Define how model field values should be rendered in the admin. The `display_class` should be a subclass of `wagtail.admin.ui.components.Component` that takes a single argument in its constructor: the value of the field. This is mainly useful for defining how fields are rendered in the inspect view, but it can also be used in other places, e.g. listing views.
def register_display_class(field_class, to=None, display_class=None, exact_class=False): """ Define how model field values should be rendered in the admin. The `display_class` should be a subclass of `wagtail.admin.ui.components.Component` that takes a single argument in its constructor: the value of the field. This is mainly useful for defining how fields are rendered in the inspect view, but it can also be used in other places, e.g. listing views. """ if display_class is None: raise ImproperlyConfigured( "register_display_class must be passed a 'display_class' keyword argument" ) if to and field_class != models.ForeignKey: raise ImproperlyConfigured( "The 'to' argument on register_display_class is only valid for ForeignKey fields" ) display_class_registry.register( field_class, to=to, value=display_class, exact_class=exact_class )
Returns boolean indicating of the user can choose page. will check if the root page can be selected and if user permissions should be checked.
def can_choose_page( page, user, desired_classes, can_choose_root=True, user_perm=None, target_pages=None, match_subclass=True, ): """Returns boolean indicating of the user can choose page. will check if the root page can be selected and if user permissions should be checked. """ if not target_pages: target_pages = [] if not match_subclass and page.specific_class not in desired_classes: return False elif ( match_subclass and not issubclass(page.specific_class or Page, desired_classes) and not desired_classes == (Page,) ): return False elif not can_choose_root and page.is_root(): return False if user_perm in ["move_to", "bulk_move_to"]: pages_to_move = target_pages for page_to_move in pages_to_move: if page.pk == page_to_move.pk or page.is_descendant_of(page_to_move): return False if user_perm == "move_to": return page_to_move.permissions_for_user(user).can_move_to(page) if user_perm in {"add_subpage", "copy_to"}: return page.permissions_for_user(user).can_add_subpage() return True
Called whenever a request comes in with the correct prefix (eg /admin/) but doesn't actually correspond to a Wagtail view. For authenticated users, it'll raise a 404 error. Anonymous users will be redirected to the login page.
def default(request): """ Called whenever a request comes in with the correct prefix (eg /admin/) but doesn't actually correspond to a Wagtail view. For authenticated users, it'll raise a 404 error. Anonymous users will be redirected to the login page. """ raise Http404
helper function: given a task, return the response indicating that it has been chosen
def get_task_chosen_response(request, task): """ helper function: given a task, return the response indicating that it has been chosen """ result_data = { "id": task.id, "name": task.name, "edit_url": reverse("wagtailadmin_workflows:edit_task", args=[task.id]), } return render_modal_workflow( request, None, None, None, json_data={"step": "task_chosen", "result": result_data}, )
Tuples of (site root page path, site display name) for all sites in project.
def _get_site_choices(): """Tuples of (site root page path, site display name) for all sites in project.""" choices = [ (site.root_page.path, str(site)) for site in Site.objects.all().select_related("root_page") ] return choices
Parses the ?fields= GET parameter. As this parameter is supposed to be used by developers, the syntax is quite tight (eg, not allowing any whitespace). Having a strict syntax allows us to extend the it at a later date with less chance of breaking anyone's code. This function takes a string and returns a list of tuples representing each top-level field. Each tuple contains three items: - The name of the field (string) - Whether the field has been negated (boolean) - A list of nested fields if there are any, None otherwise Some examples of how this function works: >>> parse_fields_parameter("foo") [ ('foo', False, None), ] >>> parse_fields_parameter("foo,bar") [ ('foo', False, None), ('bar', False, None), ] >>> parse_fields_parameter("-foo") [ ('foo', True, None), ] >>> parse_fields_parameter("foo(bar,baz)") [ ('foo', False, [ ('bar', False, None), ('baz', False, None), ]), ] It raises a FieldsParameterParseError (subclass of ValueError) if it encounters a syntax error
def parse_fields_parameter(fields_str): """ Parses the ?fields= GET parameter. As this parameter is supposed to be used by developers, the syntax is quite tight (eg, not allowing any whitespace). Having a strict syntax allows us to extend the it at a later date with less chance of breaking anyone's code. This function takes a string and returns a list of tuples representing each top-level field. Each tuple contains three items: - The name of the field (string) - Whether the field has been negated (boolean) - A list of nested fields if there are any, None otherwise Some examples of how this function works: >>> parse_fields_parameter("foo") [ ('foo', False, None), ] >>> parse_fields_parameter("foo,bar") [ ('foo', False, None), ('bar', False, None), ] >>> parse_fields_parameter("-foo") [ ('foo', True, None), ] >>> parse_fields_parameter("foo(bar,baz)") [ ('foo', False, [ ('bar', False, None), ('baz', False, None), ]), ] It raises a FieldsParameterParseError (subclass of ValueError) if it encounters a syntax error """ def get_position(current_str): return len(fields_str) - len(current_str) def parse_field_identifier(fields_str): first_char = True negated = False ident = "" while fields_str: char = fields_str[0] if char in ["(", ")", ","]: if not ident: raise FieldsParameterParseError( "unexpected char '%s' at position %d" % (char, get_position(fields_str)) ) if ident in ["*", "_"] and char == "(": # * and _ cannot have nested fields raise FieldsParameterParseError( "unexpected char '%s' at position %d" % (char, get_position(fields_str)) ) return ident, negated, fields_str elif char == "-": if not first_char: raise FieldsParameterParseError( "unexpected char '%s' at position %d" % (char, get_position(fields_str)) ) negated = True elif char in ["*", "_"]: if ident and char == "*": raise FieldsParameterParseError( "unexpected char '%s' at position %d" % (char, get_position(fields_str)) ) ident += char elif char.isalnum() or char == "_": if ident == "*": # * can only be on its own raise FieldsParameterParseError( "unexpected char '%s' at position %d" % (char, get_position(fields_str)) ) ident += char elif char.isspace(): raise FieldsParameterParseError( "unexpected whitespace at position %d" % get_position(fields_str) ) else: raise FieldsParameterParseError( "unexpected char '%s' at position %d" % (char, get_position(fields_str)) ) first_char = False fields_str = fields_str[1:] return ident, negated, fields_str def parse_fields(fields_str, expect_close_bracket=False): first_ident = None is_first = True fields = [] while fields_str: sub_fields = None ident, negated, fields_str = parse_field_identifier(fields_str) # Some checks specific to '*' and '_' if ident in ["*", "_"]: if not is_first: raise FieldsParameterParseError( "'%s' must be in the first position" % ident ) if negated: raise FieldsParameterParseError("'%s' cannot be negated" % ident) if fields_str and fields_str[0] == "(": if negated: # Negated fields cannot contain subfields raise FieldsParameterParseError( "unexpected char '(' at position %d" % get_position(fields_str) ) sub_fields, fields_str = parse_fields( fields_str[1:], expect_close_bracket=True ) if is_first: first_ident = ident else: # Negated fields can't be used with '_' if first_ident == "_" and negated: # _,foo is allowed but _,-foo is not raise FieldsParameterParseError( "negated fields with '_' doesn't make sense" ) # Additional fields without sub fields can't be used with '*' if first_ident == "*" and not negated and not sub_fields: # *,foo(bar) and *,-foo are allowed but *,foo is not raise FieldsParameterParseError( "additional fields with '*' doesn't make sense" ) fields.append((ident, negated, sub_fields)) if fields_str and fields_str[0] == ")": if not expect_close_bracket: raise FieldsParameterParseError( "unexpected char ')' at position %d" % get_position(fields_str) ) return fields, fields_str[1:] if fields_str and fields_str[0] == ",": fields_str = fields_str[1:] # A comma can not exist immediately before another comma or the end of the string if not fields_str or fields_str[0] == ",": raise FieldsParameterParseError( "unexpected char ',' at position %d" % get_position(fields_str) ) is_first = False if expect_close_bracket: # This parser should've exited with a close bracket but instead we # hit the end of the input. Raise an error raise FieldsParameterParseError( "unexpected end of input (did you miss out a close bracket?)" ) return fields, fields_str fields, _ = parse_fields(fields_str) return fields
Parses strings into booleans using the following mapping (case-sensitive): 'true' => True 'false' => False '1' => True '0' => False
def parse_boolean(value): """ Parses strings into booleans using the following mapping (case-sensitive): 'true' => True 'false' => False '1' => True '0' => False """ if value in ["true", "1"]: return True elif value in ["false", "0"]: return False else: raise ValueError("expected 'true' or 'false', got '%s'" % value)
Translate a ValidationError instance raised against a block (which may potentially be a ValidationError subclass specialised for a particular block type) into a JSON-serialisable dict consisting of one or both of: messages: a list of error message strings to be displayed against the block blockErrors: a structure specific to the block type, containing further error objects in this format to be displayed against this block's children
def get_error_json_data(error): """ Translate a ValidationError instance raised against a block (which may potentially be a ValidationError subclass specialised for a particular block type) into a JSON-serialisable dict consisting of one or both of: messages: a list of error message strings to be displayed against the block blockErrors: a structure specific to the block type, containing further error objects in this format to be displayed against this block's children """ if hasattr(error, "as_json_data"): return error.as_json_data() else: return {"messages": error.messages}
Flatten an ErrorList instance containing any number of ValidationErrors (which may themselves contain multiple messages) into a list of error message strings. This does not consider any other properties of ValidationError other than `message`, so should not be used where ValidationError subclasses with nested block errors may be present. (In terms of StreamBlockValidationError et al: it's valid for use on non_block_errors but not block_errors)
def get_error_list_json_data(error_list): """ Flatten an ErrorList instance containing any number of ValidationErrors (which may themselves contain multiple messages) into a list of error message strings. This does not consider any other properties of ValidationError other than `message`, so should not be used where ValidationError subclasses with nested block errors may be present. (In terms of StreamBlockValidationError et al: it's valid for use on non_block_errors but not block_errors) """ return list(itertools.chain(*(err.messages for err in error_list.as_data())))
Maps the value of a block. Args: block_value: The value of the block. This would be a list or dict of children for structural blocks. block_def: The definition of the block. block_path: A '.' separated list of names of the blocks from the current block (not included) to the nested block of which the value will be passed to the operation. operation: An Operation class instance (extends `BaseBlockOperation`), which has an `apply` method for mapping values. Returns: mapped_value:
def map_block_value(block_value, block_def, block_path, operation, **kwargs): """ Maps the value of a block. Args: block_value: The value of the block. This would be a list or dict of children for structural blocks. block_def: The definition of the block. block_path: A '.' separated list of names of the blocks from the current block (not included) to the nested block of which the value will be passed to the operation. operation: An Operation class instance (extends `BaseBlockOperation`), which has an `apply` method for mapping values. Returns: mapped_value: """ # If the `block_path` length is 0, that means we've reached the end of the block path, that # is, the block where we need to apply the operation. Note that we are asking the user to # pass "item" as part of the block path for list children, so it won't give rise to any # problems here. if len(block_path) == 0: return operation.apply(block_value) # Depending on whether the block is a ListBlock, StructBlock or StreamBlock we call a # different function to alter its children. if isinstance(block_def, StreamBlock): return map_stream_block_value( block_value, operation=operation, block_def=block_def, block_path=block_path, **kwargs, ) elif isinstance(block_def, ListBlock): return map_list_block_value( block_value, operation=operation, block_def=block_def, block_path=block_path, **kwargs, ) elif isinstance(block_def, StructBlock): return map_struct_block_value( block_value, operation=operation, block_def=block_def, block_path=block_path, **kwargs, ) else: raise ValueError(f"Unexpected Structural Block: {block_value}")
Maps each child block in a StreamBlock value. Args: stream_block_value: The value of the StreamBlock, a list of child blocks block_def: The definition of the StreamBlock block_path: A '.' separated list of names of the blocks from the current block (not included) to the nested block of which the value will be passed to the operation. Returns mapped_value: The value of the StreamBlock after mapping all the children.
def map_stream_block_value(stream_block_value, block_def, block_path, **kwargs): """ Maps each child block in a StreamBlock value. Args: stream_block_value: The value of the StreamBlock, a list of child blocks block_def: The definition of the StreamBlock block_path: A '.' separated list of names of the blocks from the current block (not included) to the nested block of which the value will be passed to the operation. Returns mapped_value: The value of the StreamBlock after mapping all the children. """ mapped_value = [] for child_block in stream_block_value: if not should_alter_block(child_block["type"], block_path): mapped_value.append(child_block) else: try: child_block_def = block_def.child_blocks[child_block["type"]] except KeyError: raise InvalidBlockDefError( "No current block def named {}".format(child_block["type"]) ) mapped_child_value = map_block_value( child_block["value"], block_def=child_block_def, block_path=block_path[1:], **kwargs, ) mapped_value.append({**child_block, "value": mapped_child_value}) return mapped_value
Maps each child block in a StructBlock value. Args: stream_block_value: The value of the StructBlock, a dict of child blocks block_def: The definition of the StructBlock block_path: A '.' separated list of names of the blocks from the current block (not included) to the nested block of which the value will be passed to the operation. Returns mapped_value: The value of the StructBlock after mapping all the children.
def map_struct_block_value(struct_block_value, block_def, block_path, **kwargs): """ Maps each child block in a StructBlock value. Args: stream_block_value: The value of the StructBlock, a dict of child blocks block_def: The definition of the StructBlock block_path: A '.' separated list of names of the blocks from the current block (not included) to the nested block of which the value will be passed to the operation. Returns mapped_value: The value of the StructBlock after mapping all the children. """ mapped_value = {} for key, child_value in struct_block_value.items(): if not should_alter_block(key, block_path): mapped_value[key] = child_value else: try: child_block_def = block_def.child_blocks[key] except KeyError: raise InvalidBlockDefError(f"No current block def named {key}") altered_child_value = map_block_value( child_value, block_def=child_block_def, block_path=block_path[1:], **kwargs, ) mapped_value[key] = altered_child_value return mapped_value
Maps each child block in a ListBlock value. Args: stream_block_value: The value of the ListBlock, a list of child blocks block_def: The definition of the ListBlock block_path: A '.' separated list of names of the blocks from the current block (not included) to the nested block of which the value will be passed to the operation. Returns mapped_value: The value of the ListBlock after mapping all the children.
def map_list_block_value(list_block_value, block_def, block_path, **kwargs): """ Maps each child block in a ListBlock value. Args: stream_block_value: The value of the ListBlock, a list of child blocks block_def: The definition of the ListBlock block_path: A '.' separated list of names of the blocks from the current block (not included) to the nested block of which the value will be passed to the operation. Returns mapped_value: The value of the ListBlock after mapping all the children. """ mapped_value = [] # In case data is in old list format for child_block in formatted_list_child_generator(list_block_value): mapped_child_value = map_block_value( child_block["value"], block_def=block_def.child_block, block_path=block_path[1:], **kwargs, ) mapped_value.append({**child_block, "value": mapped_child_value}) return mapped_value
Applies changes to raw stream data Args: raw_data: The current stream data (a list of top level blocks) block_path_str: A '.' separated list of names of the blocks from the top level block to the nested block of which the value will be passed to the operation. eg:- 'simplestream.struct1' would point to, [..., { type: simplestream, value: [..., { type: struct1, value: {...} }] }] NOTE: If we're directly applying changes on the top level stream block, then this will be "". NOTE: When the path contains a ListBlock child, 'item' must be added to the block as the name of said child. eg:- 'list1.item.stream1' where the list child is a StructBlock would point to, [ ..., { type: list1, value: [ { type: item, value: { ..., stream1: [...] } }, ... ] } ] operation: A subclass of `operations.BaseBlockOperation`. It will have the `apply` method for applying changes to the matching block values. streamfield: The streamfield for which data is being migrated. This is used to get the definitions of the blocks. Returns: altered_raw_data:
def apply_changes_to_raw_data( raw_data, block_path_str, operation, streamfield, **kwargs ): """ Applies changes to raw stream data Args: raw_data: The current stream data (a list of top level blocks) block_path_str: A '.' separated list of names of the blocks from the top level block to the nested block of which the value will be passed to the operation. eg:- 'simplestream.struct1' would point to, [..., { type: simplestream, value: [..., { type: struct1, value: {...} }] }] NOTE: If we're directly applying changes on the top level stream block, then this will be "". NOTE: When the path contains a ListBlock child, 'item' must be added to the block as the name of said child. eg:- 'list1.item.stream1' where the list child is a StructBlock would point to, [ ..., { type: list1, value: [ { type: item, value: { ..., stream1: [...] } }, ... ] } ] operation: A subclass of `operations.BaseBlockOperation`. It will have the `apply` method for applying changes to the matching block values. streamfield: The streamfield for which data is being migrated. This is used to get the definitions of the blocks. Returns: altered_raw_data: """ if block_path_str == "": # If block_path_str is "", we're directly applying the operation on the top level # streamblock. block_path = [] else: block_path = block_path_str.split(".") block_def = streamfield.field.stream_block altered_raw_data = map_block_value( raw_data, block_def=block_def, block_path=block_path, operation=operation, **kwargs, ) return altered_raw_data
Converts a user entered field label to a string that is safe to use for both a HTML attribute (field's name) and a JSON key used internally to store the responses.
def get_field_clean_name(label): """ Converts a user entered field label to a string that is safe to use for both a HTML attribute (field's name) and a JSON key used internally to store the responses. """ return safe_snake_case(label)
Return a queryset of form pages that this user is allowed to access the submissions for
def get_forms_for_user(user): """ Return a queryset of form pages that this user is allowed to access the submissions for """ editable_forms = page_permission_policy.instances_user_has_permission_for( user, "change" ) editable_forms = editable_forms.filter(content_type__in=get_form_types()) # Apply hooks for fn in hooks.get_hooks("filter_form_submissions_for_user"): editable_forms = fn(user, editable_forms) return editable_forms
Call the form page's list submissions view class
def get_submissions_list_view(request, *args, **kwargs): """Call the form page's list submissions view class""" page_id = kwargs.get("page_id") form_page = get_object_or_404(Page, id=page_id).specific return form_page.serve_submissions_list_view(request, *args, **kwargs)
``routablepageurl`` is similar to ``pageurl``, but works with pages using ``RoutablePageMixin``. It behaves like a hybrid between the built-in ``reverse``, and ``pageurl`` from Wagtail. ``page`` is the RoutablePage that URLs will be generated from. ``url_name`` is a URL name defined in ``page.subpage_urls``. Positional arguments and keyword arguments should be passed as normal positional arguments and keyword arguments.
def routablepageurl(context, page, url_name, *args, **kwargs): """ ``routablepageurl`` is similar to ``pageurl``, but works with pages using ``RoutablePageMixin``. It behaves like a hybrid between the built-in ``reverse``, and ``pageurl`` from Wagtail. ``page`` is the RoutablePage that URLs will be generated from. ``url_name`` is a URL name defined in ``page.subpage_urls``. Positional arguments and keyword arguments should be passed as normal positional arguments and keyword arguments. """ request = context["request"] site = Site.find_for_request(request) base_url = page.relative_url(site, request) routed_url = page.reverse_subpage(url_name, args=args, kwargs=kwargs) if not base_url.endswith("/"): base_url += "/" return base_url + routed_url
We set an explicit pk instead of relying on auto-incrementation in migration 0004, so we need to reset the database sequence.
def reset_search_promotion_sequence(apps, schema_editor): """ We set an explicit pk instead of relying on auto-incrementation in migration 0004, so we need to reset the database sequence. """ Query = apps.get_model("wagtailsearchpromotions.Query") QueryDailyHits = apps.get_model("wagtailsearchpromotions.QueryDailyHits") statements = schema_editor.connection.ops.sequence_reset_sql( no_style(), [Query, QueryDailyHits] ) for statement in statements: schema_editor.execute(statement)
Check if a user has permission to edit this setting type
def user_can_edit_setting_type(user, model): """Check if a user has permission to edit this setting type""" return user.has_perm(f"{model._meta.app_label}.change_{model._meta.model_name}")
retrieve a content type from an app_name / model_name combo. Throw Http404 if not a valid setting type
def get_model_from_url_params(app_name, model_name): """ retrieve a content type from an app_name / model_name combo. Throw Http404 if not a valid setting type """ model = registry.get_by_natural_key(app_name, model_name) if model is None: raise Http404 return model
Creates page aliases in other locales when a page is created. Whenever a page is created under a specific locale, this signal handler creates an alias page for that page under the other locales. e.g. When an editor creates the page "blog/my-blog-post" under the English tree, this signal handler creates an alias of that page called "blog/my-blog-post" under the other locales' trees.
def after_create_page(request, page): """Creates page aliases in other locales when a page is created. Whenever a page is created under a specific locale, this signal handler creates an alias page for that page under the other locales. e.g. When an editor creates the page "blog/my-blog-post" under the English tree, this signal handler creates an alias of that page called "blog/my-blog-post" under the other locales' trees. """ if getattr(settings, "WAGTAILSIMPLETRANSLATION_SYNC_PAGE_TREE", False): # Check if the source tree needs to be synchronised into any other trees # Create aliases in all those locales for locale in Locale.objects.exclude(pk=page.locale_id): if not page.has_translation(locale): page.copy_for_translation(locale, copy_parents=True, alias=True)
Check whether there are any view restrictions on this document which are not fulfilled by the given request object. If there are, return an HttpResponse that will notify the user of that restriction (and possibly include a password / login form that will allow them to proceed). If there are no such restrictions, return None
def check_view_restrictions(document, request): """ Check whether there are any view restrictions on this document which are not fulfilled by the given request object. If there are, return an HttpResponse that will notify the user of that restriction (and possibly include a password / login form that will allow them to proceed). If there are no such restrictions, return None """ for restriction in document.collection.get_view_restrictions(): if not restriction.accept_request(request): if restriction.restriction_type == BaseViewRestriction.PASSWORD: from wagtail.forms import PasswordViewRestrictionForm form = PasswordViewRestrictionForm( instance=restriction, initial={"return_url": request.get_full_path()}, ) action_url = reverse( "wagtaildocs_authenticate_with_password", args=[restriction.id] ) password_required_template = getattr( settings, "WAGTAILDOCS_PASSWORD_REQUIRED_TEMPLATE", "wagtaildocs/password_required.html", ) if hasattr(settings, "DOCUMENT_PASSWORD_REQUIRED_TEMPLATE"): warn( "The `DOCUMENT_PASSWORD_REQUIRED_TEMPLATE` setting is deprecated - use `WAGTAILDOCS_PASSWORD_REQUIRED_TEMPLATE` instead.", category=RemovedInWagtail70Warning, ) password_required_template = getattr( settings, "DOCUMENT_PASSWORD_REQUIRED_TEMPLATE", password_required_template, ) context = {"form": form, "action_url": action_url} return TemplateResponse(request, password_required_template, context) elif restriction.restriction_type in [ BaseViewRestriction.LOGIN, BaseViewRestriction.GROUPS, ]: return require_wagtail_login(next=request.get_full_path())
Get the dotted ``app.Model`` name for the document model as a string. Useful for developers making Wagtail plugins that need to refer to the document model, such as in foreign keys, but the model itself is not required.
def get_document_model_string(): """ Get the dotted ``app.Model`` name for the document model as a string. Useful for developers making Wagtail plugins that need to refer to the document model, such as in foreign keys, but the model itself is not required. """ return getattr(settings, "WAGTAILDOCS_DOCUMENT_MODEL", "wagtaildocs.Document")
Get the document model from the ``WAGTAILDOCS_DOCUMENT_MODEL`` setting. Defaults to the standard :class:`~wagtail.documents.models.Document` model if no custom model is defined.
def get_document_model(): """ Get the document model from the ``WAGTAILDOCS_DOCUMENT_MODEL`` setting. Defaults to the standard :class:`~wagtail.documents.models.Document` model if no custom model is defined. """ from django.apps import apps model_string = get_document_model_string() try: return apps.get_model(model_string, require_ready=False) except ValueError: raise ImproperlyConfigured( "WAGTAILDOCS_DOCUMENT_MODEL must be of the form 'app_label.model_name'" ) except LookupError: raise ImproperlyConfigured( "WAGTAILDOCS_DOCUMENT_MODEL refers to model '%s' that has not been installed" % model_string )
Reverse the above additions of permissions.
def remove_document_permissions(apps, schema_editor): """Reverse the above additions of permissions.""" ContentType = apps.get_model("contenttypes.ContentType") Permission = apps.get_model("auth.Permission") document_content_type = ContentType.objects.get( model="document", app_label="wagtaildocs", ) # This cascades to Group Permission.objects.filter( content_type=document_content_type, codename__in=("add_document", "change_document", "delete_document"), ).delete()
Reverse the above additions of permissions.
def remove_choose_permission(apps, _schema_editor): """Reverse the above additions of permissions.""" ContentType = apps.get_model("contenttypes.ContentType") Permission = apps.get_model("auth.Permission") document_content_type = ContentType.objects.get( model="document", app_label="wagtaildocs", ) # This cascades to Group Permission.objects.filter( content_type=document_content_type, codename="choose_document" ).delete()
Helper to construct elements of the form <a id="1" linktype="document">document link</a> when converting from contentstate data
def document_link_entity(props): """ Helper to construct elements of the form <a id="1" linktype="document">document link</a> when converting from contentstate data """ return DOM.create_element( "a", { "linktype": "document", "id": props.get("id"), }, props["children"], )
Handle a submission of PasswordViewRestrictionForm to grant view access over a subtree that is protected by a PageViewRestriction
def authenticate_with_password(request, restriction_id): """ Handle a submission of PasswordViewRestrictionForm to grant view access over a subtree that is protected by a PageViewRestriction """ restriction = get_object_or_404(CollectionViewRestriction, id=restriction_id) if request.method == "POST": form = PasswordViewRestrictionForm(request.POST, instance=restriction) if form.is_valid(): return_url = form.cleaned_data["return_url"] if not url_has_allowed_host_and_scheme( return_url, request.get_host(), request.is_secure() ): return_url = settings.LOGIN_REDIRECT_URL restriction.mark_as_passed(request) return redirect(return_url) else: form = PasswordViewRestrictionForm(instance=restriction) action_url = reverse( "wagtaildocs_authenticate_with_password", args=[restriction.id] ) password_required_template = getattr( settings, "WAGTAILDOCS_PASSWORD_REQUIRED_TEMPLATE", "wagtaildocs/password_required.html", ) if hasattr(settings, "DOCUMENT_PASSWORD_REQUIRED_TEMPLATE"): warn( "The `DOCUMENT_PASSWORD_REQUIRED_TEMPLATE` setting is deprecated - use `WAGTAILDOCS_PASSWORD_REQUIRED_TEMPLATE` instead.", category=RemovedInWagtail70Warning, ) password_required_template = getattr( settings, "DOCUMENT_PASSWORD_REQUIRED_TEMPLATE", password_required_template, ) context = {"form": form, "action_url": action_url} return TemplateResponse(request, password_required_template, context)
Imports a finder class from a dotted path. If the dotted path points to a module, that module is imported and its "embed_finder_class" class returned. If not, this will assume the dotted path points to directly a class and will attempt to import that instead.
def import_finder_class(dotted_path): """ Imports a finder class from a dotted path. If the dotted path points to a module, that module is imported and its "embed_finder_class" class returned. If not, this will assume the dotted path points to directly a class and will attempt to import that instead. """ try: finder_module = import_module(dotted_path) return finder_module.embed_finder_class except ImportError as e: try: return import_string(dotted_path) except ImportError: raise ImportError from e
Helper to construct elements of the form <embed embedtype="media" url="https://www.youtube.com/watch?v=y8Kyi0WNg40"/> when converting from contentstate data
def media_embed_entity(props): """ Helper to construct elements of the form <embed embedtype="media" url="https://www.youtube.com/watch?v=y8Kyi0WNg40"/> when converting from contentstate data """ return DOM.create_element( "embed", { "embedtype": "media", "url": props.get("url"), }, )
Convert a Willow image format name to a content type. TODO: Replace once https://github.com/wagtail/Willow/pull/102 and a new Willow release is out
def image_format_name_to_content_type(image_format_name): """ Convert a Willow image format name to a content type. TODO: Replace once https://github.com/wagtail/Willow/pull/102 and a new Willow release is out """ if image_format_name == "svg": return "image/svg+xml" elif image_format_name == "jpeg": return "image/jpeg" elif image_format_name == "png": return "image/png" elif image_format_name == "gif": return "image/gif" elif image_format_name == "bmp": return "image/bmp" elif image_format_name == "tiff": return "image/tiff" elif image_format_name == "webp": return "image/webp" elif image_format_name == "avif": return "image/avif" elif image_format_name == "ico": return "image/x-icon" else: raise ValueError("Unknown image format name")
Obtain a valid upload path for an image file. This needs to be a module-level function so that it can be referenced within migrations, but simply delegates to the `get_upload_to` method of the instance, so that AbstractImage subclasses can override it.
def get_upload_to(instance, filename): """ Obtain a valid upload path for an image file. This needs to be a module-level function so that it can be referenced within migrations, but simply delegates to the `get_upload_to` method of the instance, so that AbstractImage subclasses can override it. """ return instance.get_upload_to(filename)
Obtain a valid upload path for an image rendition file. This needs to be a module-level function so that it can be referenced within migrations, but simply delegates to the `get_upload_to` method of the instance, so that AbstractRendition subclasses can override it.
def get_rendition_upload_to(instance, filename): """ Obtain a valid upload path for an image rendition file. This needs to be a module-level function so that it can be referenced within migrations, but simply delegates to the `get_upload_to` method of the instance, so that AbstractRendition subclasses can override it. """ return instance.get_upload_to(filename)
Obtain the storage object for an image rendition file. Returns custom storage (if defined), or the default storage. This needs to be a module-level function, because we do not yet have an instance when Django loads the models.
def get_rendition_storage(): """ Obtain the storage object for an image rendition file. Returns custom storage (if defined), or the default storage. This needs to be a module-level function, because we do not yet have an instance when Django loads the models. """ storage = getattr(settings, "WAGTAILIMAGES_RENDITION_STORAGE", default_storage) if isinstance(storage, str): try: # First see if the string is a storage alias storage = storages[storage] except InvalidStorageError: # Otherwise treat the string as a dotted path try: module = import_string(storage) storage = module() except ImportError: raise ImproperlyConfigured( "WAGTAILIMAGES_RENDITION_STORAGE must be either a valid storage alias or dotted module path." ) return storage
Sets the permission policy for the current image model.
def set_permission_policy(): """Sets the permission policy for the current image model.""" global permission_policy permission_policy = CollectionOwnershipPermissionPolicy( get_image_model(), auth_model=Image, owner_field_name="uploaded_by_user" )
Updates the permission policy when the `WAGTAILIMAGES_IMAGE_MODEL` setting changes. This is useful in tests where we override the base image model and expect the permission policy to have changed accordingly.
def update_permission_policy(signal, sender, setting, **kwargs): """ Updates the permission policy when the `WAGTAILIMAGES_IMAGE_MODEL` setting changes. This is useful in tests where we override the base image model and expect the permission policy to have changed accordingly. """ if setting == "WAGTAILIMAGES_IMAGE_MODEL": set_permission_policy()
Tries to get / create the rendition for the image or renders a not-found image if it does not exist. :param image: AbstractImage :param specs: str or Filter :return: Rendition
def get_rendition_or_not_found(image, specs): """ Tries to get / create the rendition for the image or renders a not-found image if it does not exist. :param image: AbstractImage :param specs: str or Filter :return: Rendition """ try: return image.get_rendition(specs) except SourceImageIOError: # Image file is (probably) missing from /media/original_images - generate a dummy # rendition so that we just output a broken image, rather than crashing out completely # during rendering. Rendition = ( image.renditions.model ) # pick up any custom Image / Rendition classes that may be in use rendition = Rendition(image=image, width=0, height=0) rendition.file.name = "not-found" return rendition
Like get_rendition_or_not_found, but for multiple renditions. Tries to get / create the renditions for the image or renders not-found images if the image does not exist. :param image: AbstractImage :param specs: iterable of str or Filter
def get_renditions_or_not_found(image, specs): """ Like get_rendition_or_not_found, but for multiple renditions. Tries to get / create the renditions for the image or renders not-found images if the image does not exist. :param image: AbstractImage :param specs: iterable of str or Filter """ try: return image.get_renditions(*specs) except SourceImageIOError: Rendition = image.renditions.model rendition = Rendition(image=image, width=0, height=0) rendition.file.name = "not-found" return { spec if isinstance(spec, str) else spec.spec: rendition for spec in specs }
Parses a string a user typed into a tuple of 3 integers representing the red, green and blue channels respectively. May raise a ValueError if the string cannot be parsed. The colour string must be a CSS 3 or 6 digit hex code without the '#' prefix.
def parse_color_string(color_string): """ Parses a string a user typed into a tuple of 3 integers representing the red, green and blue channels respectively. May raise a ValueError if the string cannot be parsed. The colour string must be a CSS 3 or 6 digit hex code without the '#' prefix. """ if len(color_string) == 3: r = int(color_string[0], 16) * 17 g = int(color_string[1], 16) * 17 b = int(color_string[2], 16) * 17 elif len(color_string) == 6: r = int(color_string[0:2], 16) g = int(color_string[2:4], 16) b = int(color_string[4:6], 16) else: raise ValueError("Color string must be either 3 or 6 hexadecimal digits long") return r, g, b
Finds all the duplicates of a given image. To keep things simple, two images are considered to be duplicates if they have the same `file_hash` value. This function also ensures that the `user` can choose one of the duplicate images returned (if any).
def find_image_duplicates(image, user, permission_policy): """ Finds all the duplicates of a given image. To keep things simple, two images are considered to be duplicates if they have the same `file_hash` value. This function also ensures that the `user` can choose one of the duplicate images returned (if any). """ instances = permission_policy.instances_user_has_permission_for(user, "choose") return instances.exclude(pk=image.pk).filter(file_hash=image.file_hash)
Remove any directives that would require an SVG to be rasterised
def to_svg_safe_spec(filter_specs): """ Remove any directives that would require an SVG to be rasterised """ if isinstance(filter_specs, str): filter_specs = filter_specs.split("|") svg_preserving_specs = [ "max", "min", "width", "height", "scale", "fill", "original", ] safe_specs = [ x for x in filter_specs if any(x.startswith(prefix) for prefix in svg_preserving_specs) ] return "|".join(safe_specs)
Get the dotted ``app.Model`` name for the image model as a string. Useful for developers making Wagtail plugins that need to refer to the image model, such as in foreign keys, but the model itself is not required.
def get_image_model_string(): """ Get the dotted ``app.Model`` name for the image model as a string. Useful for developers making Wagtail plugins that need to refer to the image model, such as in foreign keys, but the model itself is not required. """ return getattr(settings, "WAGTAILIMAGES_IMAGE_MODEL", "wagtailimages.Image")
Get the image model from the ``WAGTAILIMAGES_IMAGE_MODEL`` setting. Useful for developers making Wagtail plugins that need the image model. Defaults to the standard :class:`~wagtail.images.models.Image` model if no custom model is defined.
def get_image_model(): """ Get the image model from the ``WAGTAILIMAGES_IMAGE_MODEL`` setting. Useful for developers making Wagtail plugins that need the image model. Defaults to the standard :class:`~wagtail.images.models.Image` model if no custom model is defined. """ from django.apps import apps model_string = get_image_model_string() try: return apps.get_model(model_string, require_ready=False) except ValueError: raise ImproperlyConfigured( "WAGTAILIMAGES_IMAGE_MODEL must be of the form 'app_label.model_name'" ) except LookupError: raise ImproperlyConfigured( "WAGTAILIMAGES_IMAGE_MODEL refers to model '%s' that has not been installed" % model_string )
Reverse the above additions of permissions.
def remove_image_permissions(apps, schema_editor): """Reverse the above additions of permissions.""" ContentType = apps.get_model("contenttypes.ContentType") Permission = apps.get_model("auth.Permission") image_content_type = ContentType.objects.get( model="image", app_label="wagtailimages", ) # This cascades to Group Permission.objects.filter( content_type=image_content_type, codename__in=("add_image", "change_image", "delete_image"), ).delete()
Reverse the above additions of permissions.
def remove_image_permissions(apps, schema_editor): """Reverse the above additions of permissions.""" ContentType = apps.get_model("contenttypes.ContentType") Permission = apps.get_model("auth.Permission") image_content_type = ContentType.objects.get( model="image", app_label="wagtailimages", ) # This cascades to Group Permission.objects.filter( content_type=image_content_type, codename__in=("add_image", "change_image", "delete_image"), ).delete()
This is a no-op. The migration removes duplicates, we cannot recreate those duplicates.
def reverse_remove_duplicate_renditions(*args, **kwargs): """This is a no-op. The migration removes duplicates, we cannot recreate those duplicates.""" pass
Reverse the above additions of permissions.
def remove_choose_permission(apps, _schema_editor): """Reverse the above additions of permissions.""" ContentType = apps.get_model("contenttypes.ContentType") Permission = apps.get_model("auth.Permission") image_content_type = ContentType.objects.get( model="image", app_label="wagtailimages", ) # This cascades to Group Permission.objects.filter( content_type=image_content_type, codename="choose_image" ).delete()
Helper to construct elements of the form <embed alt="Right-aligned image" embedtype="image" format="right" id="1"/> when converting from contentstate data
def image_entity(props): """ Helper to construct elements of the form <embed alt="Right-aligned image" embedtype="image" format="right" id="1"/> when converting from contentstate data """ return DOM.create_element( "embed", { "embedtype": "image", "format": props.get("format"), "id": props.get("id"), "alt": props.get("alt"), }, )
Image tag parser implementation. Shared between all image tags supporting filter specs as space-separated arguments.
def image(parser, token): """ Image tag parser implementation. Shared between all image tags supporting filter specs as space-separated arguments. """ tag_name, *bits = token.split_contents() image_expr = parser.compile_filter(bits[0]) bits = bits[1:] filter_specs = [] attrs = {} output_var_name = None as_context = False # if True, the next bit to be read is the output variable name error_messages = [] multi_rendition = tag_name != "image" preserve_svg = False for bit in bits: if bit == "as": # token is of the form {% image self.photo max-320x200 as img %} as_context = True elif as_context: if output_var_name is None: output_var_name = bit else: # more than one item exists after 'as' - reject as invalid error_messages.append("More than one variable name after 'as'") elif bit == "preserve-svg": preserve_svg = True else: try: name, value = bit.split("=") attrs[name] = parser.compile_filter( value ) # setup to resolve context variables as value except ValueError: allowed_pattern = ( Filter.expanding_spec_pattern if multi_rendition else Filter.spec_pattern ) if allowed_pattern.match(bit): filter_specs.append(bit) else: raise template.TemplateSyntaxError( "filter specs in image tags may only contain A-Z, a-z, 0-9, dots, hyphens and underscores (and commas and curly braces for multi-image tags). " "(given filter: {})".format(bit) ) if as_context and output_var_name is None: # context was introduced but no variable given ... error_messages.append("Missing a variable name after 'as'") if output_var_name and attrs: # attributes are not valid when using the 'as img' form of the tag error_messages.append("Do not use attributes with 'as' context assignments") if len(filter_specs) == 0: # there must always be at least one filter spec provided error_messages.append("Image tags must be used with at least one filter spec") if len(error_messages) == 0: Node = { "image": ImageNode, "srcset_image": SrcsetImageNode, "picture": PictureNode, } return Node[tag_name]( image_expr, filter_specs, attrs=attrs, output_var_name=output_var_name, preserve_svg=preserve_svg, ) else: errors = "; ".join(error_messages) raise template.TemplateSyntaxError( f"Invalid arguments provided to {tag_name}: {errors}. " 'Image tags should be of the form {% image self.photo max-320x200 [ custom-attr="value" ... ] %} ' "or {% image self.photo max-320x200 as img %}. " )
Get the generated filename for a resized image
def get_test_image_filename(image, filterspec): """ Get the generated filename for a resized image """ name, ext = os.path.splitext(os.path.basename(image.file.name)) # Use the correct extension if the filterspec is a format operation. if "format-" in filterspec: ext = "." + filterspec.split("format-")[1].split("-")[0].split(".")[0].replace( "jpeg", "jpg" ) return f"{settings.MEDIA_URL}images/{name}.{filterspec}{ext}"
Returns the number of pages and other objects that use a locale
def get_locale_usage(locale): """ Returns the number of pages and other objects that use a locale """ num_pages = Page.objects.filter(locale=locale).exclude(depth=1).count() num_others = 0 for model in get_translatable_models(): if model is Page: continue num_others += model.objects.filter(locale=locale).count() return num_pages, num_others
Treebeard's path comparison logic can fail on certain locales such as sk_SK, which sort numbers after letters. To avoid this, we explicitly set the collation for the 'path' column to the (non-locale-specific) 'C' collation. See: https://groups.google.com/d/msg/wagtail/q0leyuCnYWI/I9uDvVlyBAAJ
def set_page_path_collation(apps, schema_editor): """ Treebeard's path comparison logic can fail on certain locales such as sk_SK, which sort numbers after letters. To avoid this, we explicitly set the collation for the 'path' column to the (non-locale-specific) 'C' collation. See: https://groups.google.com/d/msg/wagtail/q0leyuCnYWI/I9uDvVlyBAAJ """ if schema_editor.connection.vendor == "postgresql": schema_editor.execute( """ ALTER TABLE wagtailcore_page ALTER COLUMN path TYPE VARCHAR(255) COLLATE "C" """ )
This function does nothing. The below code is commented out together with an explanation of why we don't need to bother reversing any of the initial data
def remove_initial_data(apps, schema_editor): """This function does nothing. The below code is commented out together with an explanation of why we don't need to bother reversing any of the initial data""" pass
Treebeard's path comparison logic can fail on certain locales such as sk_SK, which sort numbers after letters. To avoid this, we explicitly set the collation for the 'path' column to the (non-locale-specific) 'C' collation. See: https://groups.google.com/d/msg/wagtail/q0leyuCnYWI/I9uDvVlyBAAJ
def set_page_path_collation(apps, schema_editor): """ Treebeard's path comparison logic can fail on certain locales such as sk_SK, which sort numbers after letters. To avoid this, we explicitly set the collation for the 'path' column to the (non-locale-specific) 'C' collation. See: https://groups.google.com/d/msg/wagtail/q0leyuCnYWI/I9uDvVlyBAAJ """ if schema_editor.connection.vendor == "postgresql": schema_editor.execute( """ ALTER TABLE wagtailcore_page ALTER COLUMN path TYPE VARCHAR(255) COLLATE "C" """ )
This function does nothing. The below code is commented out together with an explanation of why we don't need to bother reversing any of the initial data
def remove_initial_data(apps, schema_editor): """This function does nothing. The below code is commented out together with an explanation of why we don't need to bother reversing any of the initial data""" pass