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 ful...
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 ...
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", ...
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_over...
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_...
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 i...
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", ...
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, ...
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...
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_panel...
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 iss...
<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.c...
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_d...
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(co...
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 isinstan...
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 avai...
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 ...
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"wa...
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(classna...
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...
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. """...
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 unsa...
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 ...
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. """ ...
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=va...
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: p...
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 ...
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 th...
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 t...
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 si...
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") a...
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_userpr...
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 sc...
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 c...
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:...
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-...
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") ...
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 simpli...
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/254c720e6bb02eb46ae07d10486...
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 htt...
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 ...
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 f...
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", ...
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|...
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] ...
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...
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 ...
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 th...
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. ...
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 r...
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...
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 ...
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 el...
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 speci...
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 di...
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 err...
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 ...
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 ...
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. blo...
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 nest...
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 bloc...
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 nest...
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 bloc...
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 blo...
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: ...
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:- 'simplestrea...
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 fr...
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...
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``. Positio...
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...
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("wagtailsearchpr...
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 th...
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...
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...
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 tha...
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, "WAGTAILDO...
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...
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="wa...
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="wagt...
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"), ...
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 == "...
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 instea...
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", ...
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...
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. ...
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 subclas...
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,...
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 ==...
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 Sou...
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 """ ...
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. """...
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 ...
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", ...
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_IMAG...
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 impo...
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="wagtailimag...
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="wagtailimag...
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="wagtailima...
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"...
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 = {} ...
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.s...
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_othe...
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.g...
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.g...
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