Les utilitaires (utils/)

Module situé dans zds/utils/. Il regroupe certaines fonctions et objets utiles à tout les autres modules.

Modèles (models.py)

class zds.utils.models.Alert(*args, **kwargs)

Alerts on all kinds of Comments and PublishedContents.

exception DoesNotExist
exception MultipleObjectsReturned
get_comment_subclass()

Used to retrieve comment URLs (simple call to get_absolute_url doesn’t work: objects are retrived as Comment and not subclasses) As real Comment implementation (subclasses) can’t be hard-coded due to unresolvable import loops, use InheritanceManager from django-model- utils.

is_automated()

Returns true if this alert was opened automatically.

solve(moderator, resolve_reason='', msg_title='', msg_content='')

Solve the alert and send a private message to the author if a reason is given

Paramètres:

resolve_reason (str) – reason

class zds.utils.models.Category(*args, **kwargs)

Common category for several concepts of the application.

exception DoesNotExist
exception MultipleObjectsReturned
class zds.utils.models.CategorySubCategory(*args, **kwargs)

ManyToMany between Category and SubCategory but save a boolean to know if category is his main category.

exception DoesNotExist
exception MultipleObjectsReturned
class zds.utils.models.Comment(*args, **kwargs)

Comment in forum, articles, tutorial, chapter, etc.

exception DoesNotExist
exception MultipleObjectsReturned
get_dislikers()

Get the list of the users that disliked this Comment

get_likers()

Get the list of the users that liked this Comment

get_user_vote(user)

Get a user vote (like, dislike or neutral)

get_votes(type=None)

Get the non-anonymous votes

hide_comment_by_user(user, text_hidden)

Hide a comment and save it

Paramètres:
  • user – the user that hid the comment

  • text_hidden – the hide reason

Renvoie:

save(*args, **kwargs)

We override the save method for two tasks: 1. we want to analyze the pings in the message to know if notifications needs to be created; 2. if this comment is marked as potential spam, we need to open an alert in case of update by its author.

set_user_vote(user, vote)

Set a user vote (like, dislike or neutral)

update_content(text, on_error=None)

Updates the content of this comment.

This method will render the new comment to HTML, store the rendered version, and store data to later analyze pings and spam.

This method updates fields, but does not save the instance.

Paramètres:
  • text – The new comment content.

  • on_error – A callable called if zmd returns an error, provided with a single argument: a list of user-friendly errors. See render_markdown.

class zds.utils.models.CommentEdit(*args, **kwargs)

Archive for editing a comment.

exception DoesNotExist
exception MultipleObjectsReturned
class zds.utils.models.CommentVote(*args, **kwargs)

Set of comment votes.

exception DoesNotExist
exception MultipleObjectsReturned
class zds.utils.models.Hat(*args, **kwargs)

Hats are labels that users can add to their messages. Each member can be allowed to use several hats. A hat may also be linked to a group, which allows all members of the group to use it. It can be used for exemple to allow members to identify that a moderation message was posted by a staff member.

exception DoesNotExist
exception MultipleObjectsReturned
get_users()

Return all users being allowed to use this hat.

class zds.utils.models.HatRequest(*args, **kwargs)

A hat requested by a user.

exception DoesNotExist
exception MultipleObjectsReturned
get_hat(create=False)

Get hat that matches this request. If it doesn’t exist, it is created or None is returned according to the create parameter.

notify_member()

Notify the request author about the decision that has been made.

solve(is_granted, moderator=None, comment='', hat_name=None)

Solve a hat request by granting or denying the requested hat according to the is_granted parameter.

class zds.utils.models.Licence(*args, **kwargs)

Publication licence.

exception DoesNotExist
exception MultipleObjectsReturned
class zds.utils.models.SubCategory(*args, **kwargs)

Common subcategory for several concepts of the application.

exception DoesNotExist
exception MultipleObjectsReturned
get_parent_category()

Get the parent of the category.

Renvoie:

the parent category.

Type renvoyé:

Category

class zds.utils.models.Tag(*args, **kwargs)

Set of tags.

exception DoesNotExist
exception MultipleObjectsReturned
save(*args, **kwargs)

Save the current instance. Override this in a subclass if you want to control the saving process.

The “force_insert” and “force_update” parameters can be used to insist that the « save » must be an SQL insert or update (or equivalent for non-SQL backends), respectively. Normally, they should not be set.

zds.utils.models.get_hat_from_request(request, author=None)

Return a hat that will be used for a post. This checks that the user is allowed to use this hat.

zds.utils.models.get_hat_to_add(hat_name, user)

Return a hat that will be added to a user. This function creates the hat if it does not exist, so be sure you will need it!

zds.utils.models.image_path_category(instance, filename)

Return path to an image.

zds.utils.models.image_path_help(instance, filename)

Return path to an image.

zds.utils.models.prevent_users_getting_hat_linked_to_group(sender, instance, **kwargs)

When a hat is saved with a linked group, all users that have gotten it by another way lose it to prevent a hat from being linked to a user through their profile and one of their groups. Hat requests for this hat are also canceled.

Les processeurs de contexte (context_processor.py)

La doc de Django explique le principe des context_processors comme suit :

Un processeur de contexte possède une interface très simple : ce n’est qu’une fonction Python acceptant un paramètre, un objet HttpRequest, et renvoyant un dictionnaire qui est ensuite ajouté au contexte de gabarit. Chaque processeur de contexte doit renvoyer un dictionnaire.

Les processeurs de contexte personnalisés peuvent se trouver n’importe où dans le code. Tout ce que Django demande, c’est que le réglage TEMPLATE_CONTEXT_PROCESSORS contienne le chemin vers le processeur personnalisé.

(pour plus de détails, voir la documenation de Django à ce sujet)

zds.utils.context_processor.app_settings(request)

A context processor with all APP settings.

zds.utils.context_processor.get_version()

Retrieve version informations from zds/_version.py.

zds.utils.context_processor.version(request)

A context processor to include the app version on all pages.

Utilitaires pour formulaires (forms.py)

class zds.utils.forms.CommonLayoutEditor(*args, **kwargs)
class zds.utils.forms.CommonLayoutVersionEditor(*args, send_label='Envoyer', display_save=False, **kwargs)
class zds.utils.forms.IncludeEasyMDE(*args, **kwargs)

Include EasyMDE JS File for this form

class zds.utils.forms.PasswordRequiredForm(data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=<class 'django.forms.utils.ErrorList'>, label_suffix=None, empty_permitted=False, field_order=None, use_required_attribute=None, renderer=None)
clean()

Hook for doing any extra form-wide cleaning after Field.clean() has been called on every field. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field named “__all__”.

property media

Return all media required to render the widgets on this form.

class zds.utils.forms.TagValidator

validate tags

validate_length(tag)

Check the length is in correct range. See Tag.label max length to have the true upper bound.

Paramètres:

tag – the tag lavel to validate

Renvoie:

True if length is valid

validate_no_empty_slug(tag)

Validate whether the tag slug is good

Paramètres:

tag

Renvoie:

True if the tag slug is good

validate_raw_string(raw_string)

validate a string composed as tag1,tag2.

Paramètres:

raw_string (basestring) – the string to be validate. If None this is considered as a empty str.

Renvoie:

True if raw_string is fully valid, False if at least one error appears. See self.errors to get all internationalized error.

validate_string_list(string_list)

Same as validate_raw_string but with a list of tag labels.

Paramètres:

string_list

Renvoie:

True if v is fully valid, False if at least one error appears. See self.errors to get all internationalized error.

validate_utf8mb4(tag)

Checks the tag does not contain utf8mb4 chars.

Paramètres:

tag

Renvoie:

True if no utf8mb4 string is found

Autres (misc.py)

zds.utils.misc.check_essential_accounts()

Verify that essential accounts are present in the database. Raise an exception if it is not the case.

zds.utils.misc.compute_hash(filenames)

returns a md5 hexdigest of group of files to check if they have change

zds.utils.misc.contains_utf8mb4(s)

Check if this string contains at least one character of more than 3 bytes.

zds.utils.misc.convert_camel_to_underscore(camel_case)

Converts a name in camel case to underscore.

zds.utils.misc.has_changed(instance, field, manager='objects')

Returns true if a field has changed in a model May be used in a model.save() method.

zds.utils.misc.is_ajax(request: HttpRequest)

Check whether the request was sent asynchronously.

The function returns True for :

  • requests sent using jQuery.ajax() since it sets the header X-Requested-With to XMLHttpRequest by default ;

  • requests sent using the tools provided by ajax.js, which reproduce the behavior described above to ease the progressive removal of jQuery from the codebase.

The function returns False for requests without the appropriate header. These requests will not be recognized as AJAX.

The function replaces request.is_ajax(), which is removed starting from Django 4.0.

zds.utils.misc.remove_utf8mb4(s)

Remove characters of more than 3 bytes.