Utils

This package contains utilities which facilitate specific tasks and can be re-used and imported from different locations.

Account Activation Token Generator

This module contains helpers for the account activation process (also see AccountActivationView).

class integreat_cms.cms.utils.account_activation_token_generator.AccountActivationTokenGenerator[source]

Bases: PasswordResetTokenGenerator

This token generator is identical to the default password reset token generator of django.contrib.auth with the exception of the used HMAC salt. This means password reset tokens are no longer accepted for the account activation and vice versa.

key_salt = 'integreat_cms.cms.utils.account_activation_token_generator.AccountActivationTokenGenerator'[source]

The key salt which is passed to the HMAC function

integreat_cms.cms.utils.account_activation_token_generator.account_activation_token_generator = <integreat_cms.cms.utils.account_activation_token_generator.AccountActivationTokenGenerator object>[source]

The token generator for the account activation process (an instance of AccountActivationTokenGenerator)

Content Edit Lock

This file contains a mechanism to lock a content editor for other people while a person is using it.

integreat_cms.cms.utils.content_edit_lock.get_cache_key(id_: int | str, type_: str) str[source]

This function returns the key that is used to lock a content object in the cache. It should not be used outside of this module.

Parameters:
  • id – The id of the content object

  • type – The type of the content object

  • id_ (int | str)

  • type_ (str)

Returns:

The key to use

Return type:

str

integreat_cms.cms.utils.content_edit_lock.get_locking_user(id_: int | str | None, type_: str) User | None[source]

This function returns the user that locks a specific object

Parameters:
  • id – The id of the content object or None

  • type – The type of the content object

  • id_ (int | str | None)

  • type_ (str)

Returns:

The user that holds the lock for this content object or None

Return type:

User | None

integreat_cms.cms.utils.content_edit_lock.lock_content(id_: int | None, type_: str, user: User) bool[source]

This function tries to lock a content object for a user. If it is already locked by someone else, nothing will happen. If it is already locked by the same user, the timeout gets reset.

Parameters:
  • id – The id of the content object or None

  • type – The type of the content object

  • user (User) – The user that should get unique access to this content object

  • id_ (int | None)

  • type_ (str)

Returns:

Whether the content object could be locked

Return type:

bool

integreat_cms.cms.utils.content_edit_lock.unlock_content(id_: int | None, type_: str, user: User) bool[source]

This function tries to unlock a content object for a user. If it is not locked by the passed user, nothing will happen.

Parameters:
  • id – The id of the content object or None

  • type – The type of the content object

  • user (User) – The user that wants to release the lock

  • id_ (int | None)

  • type_ (str)

Returns:

Whether the content object could be unlocked

Return type:

bool

Content Translation Utils

This file contains utility functions for content translations.

integreat_cms.cms.utils.content_translation_utils.get_referencing_translations(content_translation: AbstractContentTranslation) set[AbstractContentTranslation][source]

Returns a list of content translations that link to the given translation

Parameters:

content_translation (AbstractContentTranslation) – The content_translation for which links should be searched

Returns:

All referencing content translations

Return type:

set[AbstractContentTranslation]

integreat_cms.cms.utils.content_translation_utils.update_links_to(content_translation: AbstractContentTranslation, user: User | None) None[source]

Updates all content translations with links that point to the given translation. This fixes potentially outdated links.

Parameters:
  • content_translation (AbstractContentTranslation) – The content translation for which links that points to it should get updated

  • user (User | None) – The user who should be responsible for updating the links

Return type:

None

Content Utils

integreat_cms.cms.utils.content_utils.clean_content(content: str, language_slug: str) str[source]

This is the super function to clean content

Parameters:
  • content (str) – the body of content that should be cleaned

  • language_slug (str) – Slug of the current language

Return type:

str

integreat_cms.cms.utils.content_utils.convert_heading(content: HtmlElement) None[source]

Converts every h1 tag in the content to a h2 for SEO purposes.

Parameters:

content (HtmlElement) – the body of content of which every h1 should be converted to an h2.

Return type:

None

integreat_cms.cms.utils.content_utils.convert_monospaced_tags(content: HtmlElement) None[source]

Converts pre and code tags to p tags.

Parameters:

content (HtmlElement) – the body of content of which every pre and code tag should be transformed

Return type:

None

integreat_cms.cms.utils.content_utils.fix_alt_texts(content: HtmlElement) None[source]

This function processes images by scanning for media files and replacing alt texts.

Parameters:

content (HtmlElement) – The body of content of which the images should be processed.

Return type:

None

integreat_cms.cms.utils.content_utils.fix_notranslate(content: HtmlElement) None[source]

This function normalizes every notranslate tag, assuring notranslate class, translate attribute and dir=ltr are set.

Parameters:

content (HtmlElement) – The body of content of which the notranslate markers should be processed.

Return type:

None

integreat_cms.cms.utils.content_utils.hide_anchor_tag_around_image(content: HtmlElement) None[source]

This function checks whether an image tag wrapped by an anchor tag has an empty alt tag, if so it hides anchor tag from screen-reader and tab-key

Parameters:

content (HtmlElement) – the content which has an anchor tag wrapped around an img tag

Return type:

None

integreat_cms.cms.utils.content_utils.mark_external_links(link: HtmlElement) None[source]

Set class link-external for links

Parameters:

link (HtmlElement) – the link which classes should be adjusted.

Return type:

None

integreat_cms.cms.utils.content_utils.remove_target_attribute(link: HtmlElement) None[source]

Removes the target attribute of links if these links are external links

Parameters:

link (HtmlElement) – links whose targets should be removed

Return type:

None

integreat_cms.cms.utils.content_utils.update_internal_links(link: HtmlElement, language_slug: str) None[source]

Fixes broken internal links

Parameters:
  • link (HtmlElement) – link which should be checked for an internal link and then be updated

  • language_slug (str) – Slug of the current language

Return type:

None

integreat_cms.cms.utils.content_utils.update_links(content: HtmlElement, language_slug: str) None[source]

Super method that gathers all methods related to updating links

Parameters:
  • content (HtmlElement) – The content whose links should be updated

  • language_slug (str) – Slug of the current language

Return type:

None

Email Utils

integreat_cms.cms.utils.email_utils.send_mail(subject: str, email_template_name: str, html_email_template_name: str, context: dict[str, Any], recipient: str) None[source]

Sends welcome email to user with new account.

Making use of EmailMultiAlternatives and MIMEImage to send a multipart email with plain text and html version and also attach the branding logo.

Parameters:
  • subject (str) – The subject of the email

  • email_template_name (str) – The template to be used to render the text email

  • html_email_template_name (str) – The template to be used to render the HTML email

  • subject – The subject of the email

  • context (dict[str, Any]) – The template context variables

  • recipient (str) – The email address of the recipient

Return type:

None

External Calendar Utils

Utility functions for working with external calendars

class integreat_cms.cms.utils.external_calendar_utils.IcalEventData(*, event_id: str, title: str, content: str, start_date: date, start_time: time | None, end_date: date, end_time: time | None, is_all_day: bool, recurrence_rule: RecurrenceRuleData | None, categories: list[str], external_calendar_id: int)[source]

Bases: object

Holds data extracted from ical events

Parameters:
__init__(*, event_id: str, title: str, content: str, start_date: date, start_time: time | None, end_date: date, end_time: time | None, is_all_day: bool, recurrence_rule: RecurrenceRuleData | None, categories: list[str], external_calendar_id: int) None[source]
Parameters:
Return type:

None

classmethod from_ical_event(event: Component, language_slug: str, external_calendar_id: int, logger: Logger) Self[source]

Reads an ical event and constructs an instance of this class from it :param event: The ical event :param language_slug: The slug of the language of this event :param external_calendar_id: The id of the external calendar of this event :param logger: The logger to use :return: An instance of IcalEventData :raises ValueError: If the data are invalid

Parameters:
  • event (Component)

  • language_slug (str)

  • external_calendar_id (int)

  • logger (Logger)

Return type:

Self

to_event_form_data() dict[source]

Returns a dictionary of relevant data for the event form :return: Dict of relevant data

Return type:

dict

to_event_translation_form_data() dict[source]

Returns a dictionary of relevant data for the event translation form :return: Dict of relevant data

Return type:

dict

to_recurrence_rule_form_data() dict[source]

Returns a dictionary of relevant data for the recurrence rule form :return: Dict of relevant data :raises ValueError: If the recurrence rule cannot be mapped to form data

Return type:

dict

class integreat_cms.cms.utils.external_calendar_utils.RecurrenceRuleData(*, frequency: vFrequency, interval: vInt, until: vDDDTypes | None, by_day: list[vWeekday] | None, by_set_pos: vInt | None)[source]

Bases: object

This dataclass contains all relevant data for producing arguments for a recurrence rule from an ical rrule.

Parameters:
  • frequency (vFrequency)

  • interval (vInt)

  • until (vDDDTypes | None)

  • by_day (list[vWeekday] | None)

  • by_set_pos (vInt | None)

__init__(*, frequency: vFrequency, interval: vInt, until: vDDDTypes | None, by_day: list[vWeekday] | None, by_set_pos: vInt | None) None[source]
Parameters:
  • frequency (vFrequency)

  • interval (vInt)

  • until (vDDDTypes | None)

  • by_day (list[vWeekday] | None)

  • by_set_pos (vInt | None)

Return type:

None

decode_by_day() list[int][source]
Returns:

The correct cms.constants.weeks value for the day of the week

Raises:

ValueError – If the by_day value is not supported

Return type:

list[int]

decode_by_set_pos() int[source]
Returns:

The correct cms.constants.weeks value for the set pos

Raises:

ValueError – If the by_set_pos value is not supported

Return type:

int

classmethod from_ical_rrule(recurrence_rule: vRecur, logger: Logger) Self[source]

Constructs this class from an ical recurrence rule. :return: An instance of this class :raises ValueError: If the recurrence rule cannot be mapped to this class

Parameters:
  • recurrence_rule (vRecur)

  • logger (Logger)

Return type:

Self

to_form_data() dict[source]

Creates a dictionary that can be passed as form data to the recurrence rule form :return: Dict of relevant data :raises ValueError: If the recurrence rule cannot be mapped to form data

Return type:

dict

integreat_cms.cms.utils.external_calendar_utils.import_event(calendar: ExternalCalendar, event: Component, errors: list[str], logger: Logger) str | None[source]

Imports an event from the external calendar

Parameters:
  • calendar (ExternalCalendar) – The external calendar

  • event (Component) – The event that should be imported

  • errors (list[str]) – A list to which errors will be logged

  • logger (Logger) – The logger to use

Returns:

The uid of the event

Return type:

str | None

integreat_cms.cms.utils.external_calendar_utils.import_events(calendar: ExternalCalendar, logger: Logger) None[source]

Imports events from this calendar and sets or clears the errors field of the calendar

Parameters:
Return type:

None

File Utils

This module contains helpers for file handling.

integreat_cms.cms.utils.file_utils.create_zip_archive(source_file_paths: list[str], zip_file_path: str) None[source]

Create zip file from list of source files

Parameters:
  • source_file_paths (list[str]) – list of files to be zipped

  • zip_file_path (str) – path to zipped file

Return type:

None

integreat_cms.cms.utils.file_utils.extract_zip_archive(zip_file_path: str, target_directory: str, allowed_file_extensions: Any | None = None) tuple[list[str], list][source]

Extract zip file and return file paths of content. Returns a tuple of extracted and invalid files:

extracted_files, invalid_files = extract_zip_archive(zip_file_path, target_directory, allowed_file_extensions)

If want to extract all files regardless of their extension, discard the second return value:

extracted_files, _ = extract_zip_archive(zip_file_path, target_directory)
Parameters:
  • zip_file_path (str) – path to zip file

  • target_directory (str) – directory to where the files should be extracted

  • allowed_file_extensions (Any | None) – list of allowed file extensions. If None or empty list, all extensions are allowed.

Returns:

a tuple of two lists of the valid and invalid filenames

Return type:

tuple[list[str], list]

Linkcheck Utils

integreat_cms.cms.utils.linkcheck_utils.filter_urls(region_slug: str | None = None, url_filter: str | None = None, prefetch_region_links: bool = False) tuple[list[Url], dict[str, int]][source]

Filter all urls of one region by the given category

Parameters:
  • region_slug (str | None) – The slug of the current region

  • url_filter (str | None) – Which urls should be returned (one of valid, invalid, ignored, unchecked). If parameter is not in these choices or omitted, all urls are returned by default.

  • prefetch_region_links (bool) – Whether to prefetch region links

Returns:

A tuple of the requested urls and a dict containing the counters of all remaining urls

Return type:

tuple[list[Url], dict[str, int]]

integreat_cms.cms.utils.linkcheck_utils.find_target_url_per_content(search: str, replace: str, region: Region | None, link_types: list[str] | None) dict[AbstractContentTranslation, dict[str, str]][source]

returns in which translation what URL must be replaced

Parameters:
  • search (str) – The (partial) URL to search

  • replace (str) – The (partial) URL to replace

  • region (Region | None) – Optionally limit the replacement to one region (None means a global replacement)

  • link_types (list[str] | None) – Which kind of links should be replaced

Returns:

A dictionary of translations and list of before&after of ULRs

Return type:

dict[AbstractContentTranslation, dict[str, str]]

integreat_cms.cms.utils.linkcheck_utils.get_region_links(region: Region) QuerySet[source]

Returns the links of translations of the given region :param region: The region :return: A query containing the relevant links

Parameters:

region (Region)

Return type:

QuerySet

integreat_cms.cms.utils.linkcheck_utils.get_url_count(region_slug: str | None = None) dict[str, int][source]

Count all urls by status. The content objects are not prefetched because they are not needed for the counter.

Parameters:

region_slug (str | None) – The slug of the current region

Returns:

A dictionary containing the counters of all remaining urls

Return type:

dict[str, int]

integreat_cms.cms.utils.linkcheck_utils.get_urls(region_slug: str | None = None, url_ids: Any | None = None, prefetch_region_links: bool = False) list[Url] | QuerySet[Url][source]

Collect all the urls which appear in the latest versions of the contents of the region, filtered by ID or region if given.

Parameters:
  • region_slug (str | None) – The slug of the current region

  • url_ids (Any | None) – The list of requested url ids

  • prefetch_region_links (bool) – Whether to prefetch region links

Returns:

The list (or queryset) of urls

Return type:

list[Url] | QuerySet[Url]

integreat_cms.cms.utils.linkcheck_utils.log_replacement_is_starting(search: str, replace: str, region: Region | None, user: User | None) None[source]

function to log the current link replacement

Parameters:
  • search (str) – The (partial) URL to search

  • replace (str) – The (partial) URL to replace

  • region (Region | None) – Optionally limit the replacement to one region (None means a global replacement)

  • user (User | None) – The creator of the replaced translations

Return type:

None

integreat_cms.cms.utils.linkcheck_utils.replace_links(search: str, replace: str, *, region: Region | None = None, user: User | None = None, commit: bool = True, link_types: list[str] | None = None) None[source]

Perform search & replace in the content links

Parameters:
  • search (str) – The (partial) URL to search

  • replace (str) – The (partial) URL to replace

  • region (Region | None) – Optionally limit the replacement to one region (None means a global replacement)

  • user (User | None) – The creator of the replaced translations

  • commit (bool) – Whether changes should be written to the database

  • link_types (list[str] | None) – Which kind of links should be replaced

Return type:

None

Media Utils

Utility functions for the media management. Most of the functions are used to transform media data to other data types.

integreat_cms.cms.utils.media_utils.generate_thumbnail(original_image: InMemoryUploadedFile, size: int = 300, crop: bool = False) InMemoryUploadedFile | None[source]

Creates a thumbnail for a given media_file.

Parameters:
  • original_image (InMemoryUploadedFile) – Original image for the thumbnail

  • size (int) – Desired size of the thumbnail (maximum for height and with), defaults to MEDIA_THUMBNAIL_SIZE

  • crop (bool) – Whether the thumbnail should be cropped (resulting in a square regardless of the initial aspect ratio), defaults to MEDIA_THUMBNAIL_CROP

Returns:

The created thumbnail in memory

Return type:

InMemoryUploadedFile | None

MFA Utils

This module contains helpers for multi-factor-authentication tasks.

integreat_cms.cms.utils.mfa_utils.generate_challenge(challenge_len: int) str[source]

This function generates a random challenge of the given length. It consists of ascii letters and digits.

Example usage: GetMfaChallengeView

Parameters:

challenge_len (int) – The desired length of the challenge

Returns:

A random string of the requested length

Return type:

str

integreat_cms.cms.utils.mfa_utils.get_mfa_user(request: HttpRequest) User | None[source]

Get the user from the session if it exists. This method can be used for the passwordless login, as well as the usual login mode.

Parameters:

request (HttpRequest) – The current request

Returns:

The user

Return type:

User | None

PDF Utils

integreat_cms.cms.utils.pdf_utils.generate_pdf(region: Region, language_slug: str, pages: PageQuerySet) HttpResponseRedirect[source]

Function for handling a pdf export request for pages. The pages were either selected by cms user or by API request (see pdf_export()) For more information on xhtml2pdf, see xhtml2pdf documentation

Parameters:
  • region (Region) – region which requested the pdf document

  • language_slug (str) – bcp47 slug of the current language

  • pages (PageQuerySet) – at least on page to render as PDF document

Returns:

Redirection to PDF document

Return type:

HttpResponseRedirect

integreat_cms.cms.utils.pdf_utils.link_callback(uri: str, rel: str) str | None[source]

According to the xhtml2pdf documentation (see Link callback, this function is necessary for resolving the Django static files references. It returns the absolute paths to the files on the file system.

Parameters:
  • uri (str) – URI that is generated by django template tag ‘static’

  • rel (str) – The relative path directory

Returns:

The absolute path on the file system according to django’s static file settings

Return type:

str | None

Repair Tree

This module contains utilities to repair or detect inconsistencies in a tree

class integreat_cms.cms.utils.repair_tree.MPTTFixer(dj_apps: Apps = <django.apps.registry.Apps object>)[source]

Bases: object

Gets ALL nodes and coughs out fixed lft, rgt and depth values. Uses the parent field to fix hierarchy and sorts siblings by (potentially inconsistent) lft.

Parameters:

dj_apps (Apps)

__init__(dj_apps: Apps = <django.apps.registry.Apps object>) None[source]

Create a fixed tree, using a ShadowInstance of each page.

Parameters:

dj_apps (Apps)

Return type:

None

fix_values() None[source]

Recalculate lft, rgt and depth values for the reconstructed hierarchical structure.

Return type:

None

fix_values_on_subtree(node_id: int, counter: int, depth: int) int[source]

Recalculate lft, rgt and depth values for the subtree of the reconstructed hierarchical structure.

Parameters:
Return type:

int

get_fixed_root_node(page_id: int) ShadowInstance[Page][source]

Travel up ancestors of a page until we get the root node.

Parameters:

page_id (int)

Return type:

ShadowInstance[Page]

get_fixed_root_nodes() Iterable[ShadowInstance[Page]][source]

Yield all fixed root nodes.

Return type:

Iterable[ShadowInstance[Page]]

get_fixed_tree_nodes() Iterable[ShadowInstance[Page]][source]

Return all nodes of this page tree.

Return type:

Iterable[ShadowInstance[Page]]

get_fixed_tree_of_page(node_id: int | None = None) Iterable[ShadowInstance[Page]][source]

Yield all nodes of the same page tree as the node specified by id in order (fixed). If no node_id is specified, nodes from all trees are considered.

Parameters:

node_id (int | None)

Return type:

Iterable[ShadowInstance[Page]]

recreate_structure() None[source]

Extract nodes and recreate their hierarchy.

Return type:

None

yield_subtree(node_id: int) Iterable[ShadowInstance[Page]][source]

Yield all nodes of the subtree as the node specified by id in order (fixed).

Parameters:

node_id (int)

Return type:

Iterable[ShadowInstance[Page]]

integreat_cms.cms.utils.repair_tree.print_changed_fields(tree_node: ShadowInstance[Page], logging_name: str = 'integreat_cms.cms.utils.repair_tree') None[source]

Utility function to print changed and unchanged attributes using a ShadowInstance of the Page.

Parameters:
Return type:

None

integreat_cms.cms.utils.repair_tree.repair_tree(page_id: Iterable[int] | None = None, commit: bool = False, logging_name: str = 'integreat_cms.cms.utils.repair_tree', dj_apps: Apps = <django.apps.registry.Apps object>) None[source]

Fix the tree for a given page, or all trees if no id is given. Changes are only written to the database if commit is set to True. For details see MPTTFixer.

Parameters:
  • page_id (Iterable[int] | None)

  • commit (bool)

  • logging_name (str)

  • dj_apps (Apps)

Return type:

None

Round Hix Score

integreat_cms.cms.utils.round_hix_score.round_hix_score(raw_score: float | None) float | None[source]

Function to round HIX score

Parameters:

raw_score (float | None)

Return type:

float | None

Shadow Instance

This module contains utilities to repair or detect inconsistencies in a tree

class integreat_cms.cms.utils.shadow_instance.ShadowInstance(instance: T)[source]

Bases: Generic[T]

An object shadowing the attributes of the model instance passed to it on instantiation and withholding any attribute changes until explicitly applied, allowing to compare the old and new states before committing to them.

Parameters:

instance (T)

__init__(instance: T)[source]
Parameters:

instance (T)

apply_changes(attributes: Iterable | None = None) None[source]

Apply changes of the listed attributes. Applies all changes if attributes is None.

Parameters:

attributes (Iterable | None)

Return type:

None

property changed_attributes: dict[str, dict[str, Any]][source]

A dictionary of all attributes whose value is to be changed. The value to each attribute name is another dictionary containing the "old" and "new" value.

Note that this does not show attributes that were overwritten with the same value (so display no difference yet) – for this see overwritten_attributes.

discard_changes(attributes: Iterable | None = None) None[source]

Discard changes of the listed attributes. Discards all changes if attributes is None.

Parameters:

attributes (Iterable | None)

Return type:

None

property instance: T[source]

Return the shadowed instance.

property overwritten_attributes: dict[str, dict[str, Any]][source]

A dictionary of all overwritten attributes. The value to each attribute name is another dictionary containing the "old" and "new" value (missing the "old" value if the attribute is not set on the instance).

Note that this even shows attributes that were overwritten with the same value (so display no difference yet) – for only the changed values see changed_attributes.

reload() None[source]

Reload the shadowed instance from the database. The state of the overwritten attributes is kept.

This can be used to incorporate recent changes to the database object after a longer (i.e. user directed) staging period.

Return type:

None

save(*args: list, **kwargs: dict) None[source]

Save the shadowed instance. Does nothing if no changes were applied yet (see apply_changes()).

Parameters:
Return type:

None

Slug Utils

This module contains helpers regarding unique string identifiers without special characters (“slugs”).

integreat_cms.cms.utils.slug_utils.generate_unique_slug(**kwargs: Unpack[SlugKwargs]) str[source]

This function can be used in forms to clean slug fields. It will make sure the slug field contains a unique identifier per region and language. It can also be used for region slugs (foreign_model is None in this case). If the slug field is empty, it creates a fallback value from either the title or the name field. In case the slug exists already, it appends a counter which is increased until the slug is unique.

Example usages:

Parameters:

**kwargs (Unpack[SlugKwargs]) – The supplied keyword arguments

Raises:

ValidationError – When no slug is given and there is also no field which can be used as fallback (either title or name).

Returns:

An unique slug identifier

Return type:

str

integreat_cms.cms.utils.slug_utils.generate_unique_slug_helper(form_object: ModelForm, foreign_model: ForeignModelType) str[source]

This function acts like an interface and extracts all parameters of the form_object before actually generating the unique slug, so that unique slug generation can be performed without any cleaned form data after a form submission.

Parameters:
  • form_object (ModelForm) – The form which contains the slug field

  • foreign_model (ForeignModelType) – If the form instance has a foreign key to another model (e.g. because it is a translation of a content-object), this parameter contains the model of the foreign related object.

Raises:

ValidationError – When no slug is given and there is also no field which can be used as fallback (either title or name).

Returns:

An unique slug identifier

Return type:

str

Stringify List

integreat_cms.cms.utils.stringify_list.iter_to_string(iterable: Iterable, *, quotation_char: str = '"', max_items: int = 5) str[source]

This is a helper function that turns a list into a string using different delimiters.

Parameters:
  • iterable (Iterable) – List of items

  • quotation_char (str) – The character that is added around each item in the list

  • max_items (int) – The maximum number of items in the iterable to display

Returns:

Returns string with the single items separated by comma expect the last item which is separated by ‘and’.

Return type:

str

Text Utils

This module contains helpers for strings.

integreat_cms.cms.utils.text_utils.lowfirst(string: Promise) str[source]

Make the first letter of a string lowercase (counterpart of capfirst(), see also capfirst).

Parameters:

string (Promise) – The input text

Returns:

The lowercase text

Return type:

str

integreat_cms.cms.utils.text_utils.truncate_bytewise(string: str, length: int) str[source]

Truncate a UTF-8 encoded string to a maximum byte length.

Parameters:
  • string (str) – The input text

  • length (int) – The maximum length of the text in byte representation

Returns:

The truncated text

Return type:

str

Tinymce Icon Utils

This file contains utilities related to icons in the tinymce editor

integreat_cms.cms.utils.tinymce_icon_utils.get_icon_html(icon_name: str) Element[source]

Returns the html for the given icon

Parameters:

icon_name (str) – The name of the icon

Returns:

The html

Return type:

Element

integreat_cms.cms.utils.tinymce_icon_utils.get_icon_url(icon_name: str) str[source]

Returns the url to the given icon svg

Parameters:

icon_name (str) – The name of the icon

Returns:

the url path to the asset

Return type:

str

integreat_cms.cms.utils.tinymce_icon_utils.make_icon(icon_url: str) Element[source]

Construct a html element that display an image with the given url :param icon_url: The url to the icon :return: The html element

Parameters:

icon_url (str)

Return type:

Element

Totp Utils

This module contains helper functions that are used within the TOTP registration and authentication.

integreat_cms.cms.utils.totp_utils.check_totp_code(given_totp_code: str, key: str) bool[source]

Helper method to check the given code with the initial key

Parameters:
  • given_totp_code (str) – The entered TOTP code form the user

  • key (str) – The key that is used for the generation of the true code

Returns:

True if the given code matches the initiated

Return type:

bool

integreat_cms.cms.utils.totp_utils.generate_totp_qrcode(key: str, user: User) str[source]

Render event form for HTTP GET requests

Parameters:
  • key (str) – The required key to generate the QR code

  • user (User) – The user account that is trying to add TOTP to its account

Returns:

The QR code as a base64-encoded string

Return type:

str

Translation Utils

This module contains helpers for the gettext translation process of UI languages.

integreat_cms.cms.utils.translation_utils.gettext_many_lazy(*strings: Any) Promise[source]

This function is a wrapper for django.utils.text.format_lazy() for the special case that the given strings should be concatenated with a space in between. This is useful for splitting lazy translated strings by sentences which improves the translation memory.

Parameters:

*strings (Any) – A list of lazy translated strings which should be concatenated

Returns:

A lazy formatted string

Return type:

Promise

integreat_cms.cms.utils.translation_utils.translate_link(message: Promise | str, attributes: dict[str, str]) SafeString[source]

Translate a link with keeping the HTML tags and still escaping all unknown parts of the message

Parameters:
  • message (Promise | str) – The translated message that contains the link placeholder <a>{link_text}</a>

  • attributes (dict[str, str]) – A dictionary of attributes for the link

Returns:

A correctly escaped formatted string with the translated message and the HTML link

Return type:

SafeString

User Utils

integreat_cms.cms.utils.user_utils.search_users(region: Region | None, query: str) QuerySet[User][source]

Searches for all users that match the given query. If region is None, all users are searched. :param region: The current region :param query: The query string used for filtering the regions :return: A query for all matching objects

Parameters:
Return type:

QuerySet[User]

Welcome Mail Utils

integreat_cms.cms.utils.welcome_mail_utils.send_welcome_mail(request: HttpRequest, user: User, activation: bool) None[source]

Sends welcome email to user with new account.

Making use of EmailMultiAlternatives and MIMEImage to send a multipart email with plain text and html version and also attach the integreat logo.

Parameters:
  • request (HttpRequest) – The current http request

  • user (User) – The user to whom the e-mail is to be sent

  • activation (bool) – Activation link should be generated

Return type:

None