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.
- 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
- 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.
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:
- 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
- integreat_cms.cms.utils.content_utils.convert_heading(content: HtmlElement) None [source]
Converts every
h1
tag in the content to ah2
for SEO purposes.- Parameters:
content (HtmlElement) – the body of content of which every
h1
should be converted to anh2
.- Return type:
None
- integreat_cms.cms.utils.content_utils.convert_monospaced_tags(content: HtmlElement) None [source]
Converts
pre
andcode
tags top
tags.- Parameters:
content (HtmlElement) – the body of content of which every
pre
andcode
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 anddir=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
andMIMEImage
to send a multipart email with plain text and html version and also attach the branding logo.- Parameters:
- 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, 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, categories: list[str], external_calendar_id: int) None [source]
- classmethod from_ical_event(event: Component, language_slug: str, external_calendar_id: int, logger: Logger) IcalEventData [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
- Parameters:
- Return type:
- 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
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:
calendar (ExternalCalendar) – The external calendar
logger (Logger) – The logger to use
- 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
- 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:
- Returns:
a tuple of two lists of the valid and invalid filenames
- Return type:
Internal Link Checker
- integreat_cms.cms.utils.internal_link_checker.check_event_or_location(content_type: str, manager: RelatedManager, url: Url, path_components: list[str], region: Region, language: Language) bool [source]
Check whether the event or location with that URL exists in the given region and language. Fallback translations are also checked when they are enabled in the specific region.
- Parameters:
- Returns:
The validity status of the URL
- Return type:
- integreat_cms.cms.utils.internal_link_checker.check_imprint(url: Url, path_components: list[str], region: Region, language: Language) bool [source]
Check whether the imprint exists in the given region and language
- integreat_cms.cms.utils.internal_link_checker.check_internal(url: Url) bool | None [source]
- Parameters:
url (Url) – The internal URL to check
- Returns:
The status of the URL
- Return type:
bool | None
- integreat_cms.cms.utils.internal_link_checker.check_news_link(url: Url, path_components: list[str], region: Region, language: Language) bool | None [source]
Check whether the news exists in the given region
- integreat_cms.cms.utils.internal_link_checker.check_object_link(content_type: str, manager: RelatedManager, slug: str, url: Url, region: Region, language: Language) bool [source]
Check whether the given content objects are valid
- integreat_cms.cms.utils.internal_link_checker.check_offer_link(url: Url, path_components: list[str], region: Region) bool [source]
Check whether the offer exists in the given region
- integreat_cms.cms.utils.internal_link_checker.check_translation_link(content_object: Event | Page | POI, url: Url, language: Language) bool [source]
Check whether the link of the given content object is valid
Internal Link Utils
This file contains utility functions for recognizing and modifying internal links
- integreat_cms.cms.utils.internal_link_utils.get_public_translation_for_link(url: str) AbstractContentTranslation | None [source]
This function gets the public content translation object corresponding to the path of an internal url. If the url does not refer to any object, this function will return None. This function handles webapp links and short urls. If the language of the url is the same as current_language_slug, this function will return None.
- Parameters:
url (str) – The url
- Returns:
The latest corresponding content translation
- Return type:
AbstractContentTranslation | None
- integreat_cms.cms.utils.internal_link_utils.get_public_translation_for_short_link(path: str) AbstractContentTranslation | None [source]
Calculates the content object that corresponds to the short url path and returns its latest public translation.
- Parameters:
path (str) – The url path, for example given the url ‘http://localhost:8000/s/p/124/’ it would be ‘/s/p/124/’
- Returns:
The latest corresponding content translation
- Return type:
AbstractContentTranslation | None
- integreat_cms.cms.utils.internal_link_utils.get_public_translation_for_webapp_link(path: str) AbstractContentTranslation | None [source]
Calculates the content object that corresponds to the webapp url path and returns its latest public translation.
- Parameters:
path (str) – The url path, for example given the url ‘https://integreat.app/augsburg/de/willkommen/’ it would be ‘/augsburg/de/willkommen/’
- Returns:
The latest corresponding content translation
- Return type:
AbstractContentTranslation | None
- integreat_cms.cms.utils.internal_link_utils.get_public_translation_for_webapp_link_parts(region_slug: str, language_slug: str, path_parts: list[str]) AbstractContentTranslation | None [source]
Calculates the content translation that corresponds to the given path, region slug and language slug.
- Parameters:
- Return type:
AbstractContentTranslation | None
- integreat_cms.cms.utils.internal_link_utils.update_link(link: Element, target_language_slug: str) tuple[str, Element | str] | None [source]
Fixes the internal link, if it is broken. This includes:
Changing the link language to target_language_slug
Fixing the link path if any part of it points to an outdated version of a content translation
Returns a tuple of the translated url and (potentially) modified title. For example, with current_link = ‘https://integreat.app/augsburg/de/willkommen/’ and language_slug = ‘en’ a possible return value could be (’https://integreat.app/augsburg/en/welcome/, ‘Welcome’). Note that the resulting link might refer to a fallback language and not the actual target language.
Link Utils
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:
- 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:
- Returns:
A dictionary of translations and list of before&after of ULRs
- Return type:
- 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
- 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.
- 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.
- 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
- 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
- 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
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
anddepth
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
anddepth
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
anddepth
values for the subtree of the reconstructed hierarchical structure.
- 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:
- 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]]
- 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 thePage
.- Parameters:
tree_node (ShadowInstance[Page])
logging_name (str)
- 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 toTrue
. For details seeMPTTFixer
.
Round Hix Score
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
isNone
.- 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
isNone
.- 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 theinstance
).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
.
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
isNone
in this case). If the slug field is empty, it creates a fallback value from either thetitle
or thename
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
orname
).- Returns:
An unique slug identifier
- Return type:
- 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
orname
).- Returns:
An unique slug identifier
- Return type:
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:
- Returns:
Returns string with the single items separated by comma expect the last item which is separated by ‘and’.
- Return type:
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 alsocapfirst
).- Parameters:
string (Promise) – The input text
- Returns:
The lowercase text
- Return type:
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
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
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:
- 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
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
andMIMEImage
to send a multipart email with plain text and html version and also attach the integreat logo.