Aller au contenu

Models

Club

Bases: Model

The Club class, made as a tree to allow nice tidy organization.

check_loop()

Raise a validation error when a loop is found within the parent list.

Source code in club/models.py
def check_loop(self):
    """Raise a validation error when a loop is found within the parent list."""
    objs = []
    cur = self
    while cur.parent is not None:
        if cur in objs:
            raise ValidationError(_("You can not make loops in clubs"))
        objs.append(cur)
        cur = cur.parent

is_owned_by(user)

Method to see if that object can be super edited by the given user.

Source code in club/models.py
def is_owned_by(self, user):
    """Method to see if that object can be super edited by the given user."""
    if user.is_anonymous:
        return False
    return user.is_board_member

can_be_edited_by(user)

Method to see if that object can be edited by the given user.

Source code in club/models.py
def can_be_edited_by(self, user):
    """Method to see if that object can be edited by the given user."""
    return self.has_rights_in_club(user)

can_be_viewed_by(user)

Method to see if that object can be seen by the given user.

Source code in club/models.py
def can_be_viewed_by(self, user):
    """Method to see if that object can be seen by the given user."""
    sub = User.objects.filter(pk=user.pk).first()
    if sub is None:
        return False
    return sub.was_subscribed

get_membership_for(user)

Return the current membership the given user.

Note

The result is cached.

Source code in club/models.py
def get_membership_for(self, user: User) -> Membership | None:
    """Return the current membership the given user.

    Note:
        The result is cached.
    """
    if user.is_anonymous:
        return None
    membership = cache.get(f"membership_{self.id}_{user.id}")
    if membership == "not_member":
        return None
    if membership is None:
        membership = self.members.filter(user=user, end_date=None).first()
        if membership is None:
            cache.set(f"membership_{self.id}_{user.id}", "not_member")
        else:
            cache.set(f"membership_{self.id}_{user.id}", membership)
    return membership

RealGroupManager

Bases: GroupManager

MetaGroupManager

Bases: GroupManager

Group

Bases: Group

Implement both RealGroups and Meta groups.

Groups are sorted by their is_meta property

MetaGroup(*args, **kwargs)

Bases: Group

MetaGroups are dynamically created groups.

Generally used with clubs where creating a club creates two groups:

  • club-SITH_BOARD_SUFFIX
  • club-SITH_MEMBER_SUFFIX
Source code in core/models.py
def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.is_meta = True

associated_club()

Return the group associated with this meta group.

The result of this function is cached

Returns:

Type Description
Club | None

The associated club if it exists, else None

Source code in core/models.py
@cached_property
def associated_club(self) -> Club | None:
    """Return the group associated with this meta group.

    The result of this function is cached


    Returns:
        The associated club if it exists, else None
    """
    from club.models import Club

    if self.name.endswith(settings.SITH_BOARD_SUFFIX):
        # replace this with str.removesuffix as soon as Python
        # is upgraded to 3.10
        club_name = self.name[: -len(settings.SITH_BOARD_SUFFIX)]
    elif self.name.endswith(settings.SITH_MEMBER_SUFFIX):
        club_name = self.name[: -len(settings.SITH_MEMBER_SUFFIX)]
    else:
        return None
    club = cache.get(f"sith_club_{club_name}")
    if club is None:
        club = Club.objects.filter(unix_name=club_name).first()
        cache.set(f"sith_club_{club_name}", club)
    return club

RealGroup

Bases: Group

RealGroups are created by the developer.

Most of the time they match a number in settings to be easily used for permissions.

User

Bases: AbstractBaseUser

Defines the base user class, useable in every app.

This is almost the same as the auth module AbstractUser since it inherits from it, but some fields are required, and the username is generated automatically with the name of the user (see generate_username()).

Added field: nick_name, date_of_birth Required fields: email, first_name, last_name, date_of_birth

cached_groups: list[Group] property

Get the list of groups this user is in.

The result is cached for the default duration (should be 5 minutes)

Returns: A list of all the groups this user is in.

is_in_group(*, pk=None, name=None)

Check if this user is in the given group. Either a group id or a group name must be provided. If both are passed, only the id will be considered.

The group will be fetched using the given parameter. If no group is found, return False. If a group is found, check if this user is in the latter.

Returns:

Type Description
bool

True if the user is the group, else False

Source code in core/models.py
def is_in_group(self, *, pk: int = None, name: str = None) -> bool:
    """Check if this user is in the given group.
    Either a group id or a group name must be provided.
    If both are passed, only the id will be considered.

    The group will be fetched using the given parameter.
    If no group is found, return False.
    If a group is found, check if this user is in the latter.

    Returns:
         True if the user is the group, else False
    """
    if pk is not None:
        group: Optional[Group] = get_group(pk=pk)
    elif name is not None:
        group: Optional[Group] = get_group(name=name)
    else:
        raise ValueError("You must either provide the id or the name of the group")
    if group is None:
        return False
    if group.id == settings.SITH_GROUP_PUBLIC_ID:
        return True
    if group.id == settings.SITH_GROUP_SUBSCRIBERS_ID:
        return self.is_subscribed
    if group.id == settings.SITH_GROUP_OLD_SUBSCRIBERS_ID:
        return self.was_subscribed
    if group.id == settings.SITH_GROUP_ROOT_ID:
        return self.is_root
    if group.is_meta:
        # check if this group is associated with a club
        group.__class__ = MetaGroup
        club = group.associated_club
        if club is None:
            return False
        membership = club.get_membership_for(self)
        if membership is None:
            return False
        if group.name.endswith(settings.SITH_MEMBER_SUFFIX):
            return True
        return membership.role > settings.SITH_MAXIMUM_FREE_ROLE
    return group in self.cached_groups

age()

Return the age this user has the day the method is called. If the user has not filled his age, return 0.

Source code in core/models.py
@cached_property
def age(self) -> int:
    """Return the age this user has the day the method is called.
    If the user has not filled his age, return 0.
    """
    if self.date_of_birth is None:
        return 0
    today = timezone.now()
    age = today.year - self.date_of_birth.year
    # remove a year if this year's birthday is yet to come
    age -= (today.month, today.day) < (
        self.date_of_birth.month,
        self.date_of_birth.day,
    )
    return age

get_full_name()

Returns the first_name plus the last_name, with a space in between.

Source code in core/models.py
def get_full_name(self):
    """Returns the first_name plus the last_name, with a space in between."""
    full_name = "%s %s" % (self.first_name, self.last_name)
    return full_name.strip()

get_short_name()

Returns the short name for the user.

Source code in core/models.py
def get_short_name(self):
    """Returns the short name for the user."""
    if self.nick_name:
        return self.nick_name
    return self.first_name + " " + self.last_name

get_display_name()

Returns the display name of the user.

A nickname if possible, otherwise, the full name.

Source code in core/models.py
def get_display_name(self) -> str:
    """Returns the display name of the user.

    A nickname if possible, otherwise, the full name.
    """
    if self.nick_name:
        return "%s (%s)" % (self.get_full_name(), self.nick_name)
    return self.get_full_name()

get_age()

Returns the age.

Source code in core/models.py
def get_age(self):
    """Returns the age."""
    today = timezone.now()
    born = self.date_of_birth
    return (
        today.year - born.year - ((today.month, today.day) < (born.month, born.day))
    )

email_user(subject, message, from_email=None, **kwargs)

Sends an email to this User.

Source code in core/models.py
def email_user(self, subject, message, from_email=None, **kwargs):
    """Sends an email to this User."""
    if from_email is None:
        from_email = settings.DEFAULT_FROM_EMAIL
    send_mail(subject, message, from_email, [self.email], **kwargs)

generate_username()

Generates a unique username based on the first and last names.

For example: Guy Carlier gives gcarlier, and gcarlier1 if the first one exists.

Returns:

Type Description
str

The generated username.

Source code in core/models.py
def generate_username(self) -> str:
    """Generates a unique username based on the first and last names.

    For example: Guy Carlier gives gcarlier, and gcarlier1 if the first one exists.

    Returns:
        The generated username.
    """

    def remove_accents(data):
        return "".join(
            x
            for x in unicodedata.normalize("NFKD", data)
            if unicodedata.category(x)[0] == "L"
        ).lower()

    user_name = (
        remove_accents(self.first_name[0] + self.last_name)
        .encode("ascii", "ignore")
        .decode("utf-8")
    )
    un_set = [u.username for u in User.objects.all()]
    if user_name in un_set:
        i = 1
        while user_name + str(i) in un_set:
            i += 1
        user_name += str(i)
    self.username = user_name
    return user_name

is_owner(obj)

Determine if the object is owned by the user.

Source code in core/models.py
def is_owner(self, obj):
    """Determine if the object is owned by the user."""
    if hasattr(obj, "is_owned_by") and obj.is_owned_by(self):
        return True
    if hasattr(obj, "owner_group") and self.is_in_group(pk=obj.owner_group.id):
        return True
    if self.is_root:
        return True
    return False

can_edit(obj)

Determine if the object can be edited by the user.

Source code in core/models.py
def can_edit(self, obj):
    """Determine if the object can be edited by the user."""
    if hasattr(obj, "can_be_edited_by") and obj.can_be_edited_by(self):
        return True
    if hasattr(obj, "edit_groups"):
        for pk in obj.edit_groups.values_list("pk", flat=True):
            if self.is_in_group(pk=pk):
                return True
    if isinstance(obj, User) and obj == self:
        return True
    if self.is_owner(obj):
        return True
    return False

can_view(obj)

Determine if the object can be viewed by the user.

Source code in core/models.py
def can_view(self, obj):
    """Determine if the object can be viewed by the user."""
    if hasattr(obj, "can_be_viewed_by") and obj.can_be_viewed_by(self):
        return True
    if hasattr(obj, "view_groups"):
        for pk in obj.view_groups.values_list("pk", flat=True):
            if self.is_in_group(pk=pk):
                return True
    if self.can_edit(obj):
        return True
    return False

clubs_with_rights()

The list of clubs where the user has rights

Source code in core/models.py
@cached_property
def clubs_with_rights(self) -> list[Club]:
    """The list of clubs where the user has rights"""
    memberships = self.memberships.ongoing().board().select_related("club")
    return [m.club for m in memberships]

AnonymousUser()

Bases: AnonymousUser

Source code in core/models.py
def __init__(self):
    super().__init__()

is_in_group(*, pk=None, name=None)

The anonymous user is only in the public group.

Source code in core/models.py
def is_in_group(self, *, pk: int = None, name: str = None) -> bool:
    """The anonymous user is only in the public group."""
    allowed_id = settings.SITH_GROUP_PUBLIC_ID
    if pk is not None:
        return pk == allowed_id
    elif name is not None:
        group = get_group(name=name)
        return group is not None and group.id == allowed_id
    else:
        raise ValueError("You must either provide the id or the name of the group")

Preferences

Bases: Model

SithFile

Bases: Model

clean()

Cleans up the file.

Source code in core/models.py
def clean(self):
    """Cleans up the file."""
    super().clean()
    if "/" in self.name:
        raise ValidationError(_("Character '/' not authorized in name"))
    if self == self.parent:
        raise ValidationError(_("Loop in folder tree"), code="loop")
    if self == self.parent or (
        self.parent is not None and self in self.get_parent_list()
    ):
        raise ValidationError(_("Loop in folder tree"), code="loop")
    if self.parent and self.parent.is_file:
        raise ValidationError(
            _("You can not make a file be a children of a non folder file")
        )
    if (
        self.parent is None
        and SithFile.objects.exclude(id=self.id)
        .filter(parent=None, name=self.name)
        .exists()
    ) or (
        self.parent
        and self.parent.children.exclude(id=self.id).filter(name=self.name).exists()
    ):
        raise ValidationError(_("Duplicate file"), code="duplicate")
    if self.is_folder:
        if self.file:
            try:
                import imghdr

                if imghdr.what(None, self.file.read()) not in [
                    "gif",
                    "png",
                    "jpeg",
                ]:
                    self.file.delete()
                    self.file = None
            except:
                self.file = None
        self.mime_type = "inode/directory"
    if self.is_file and (self.file is None or self.file == ""):
        raise ValidationError(_("You must provide a file"))

copy_rights()

Copy, if possible, the rights of the parent folder.

Source code in core/models.py
def copy_rights(self):
    """Copy, if possible, the rights of the parent folder."""
    if self.parent is not None:
        self.edit_groups.set(self.parent.edit_groups.all())
        self.view_groups.set(self.parent.view_groups.all())
        self.save()

move_to(parent)

Move a file to a new parent. parent must be a SithFile with the is_folder=True property. Otherwise, this function doesn't change anything. This is done only at the DB level, so that it's very fast for the user. Indeed, this function doesn't modify SithFiles recursively, so it stays efficient even with top-level folders.

Source code in core/models.py
def move_to(self, parent):
    """Move a file to a new parent.
    `parent` must be a SithFile with the `is_folder=True` property. Otherwise, this function doesn't change
    anything.
    This is done only at the DB level, so that it's very fast for the user. Indeed, this function doesn't modify
    SithFiles recursively, so it stays efficient even with top-level folders.
    """
    if not parent.is_folder:
        return
    self.parent = parent
    self.clean()
    self.save()

LockError

Bases: Exception

There was a lock error on the object.

AlreadyLocked

Bases: LockError

The object is already locked.

NotLocked

Bases: LockError

The object is not locked.

Page

Bases: Model

The page class to build a Wiki Each page may have a parent and it's URL is of the form my.site/page/// It has an ID field, but don't use it, since it's only there for DB part, and because compound primary key is awkward! Prefere querying pages with Page.get_page_by_full_name().

Be careful with the _full_name attribute: this field may not be valid until you call save(). It's made for fast query, but don't rely on it when playing with a Page object, use get_full_name() instead!

save(*args, **kwargs)

Performs some needed actions before and after saving a page in database.

Source code in core/models.py
def save(self, *args, **kwargs):
    """Performs some needed actions before and after saving a page in database."""
    locked = kwargs.pop("force_lock", False)
    if not locked:
        locked = self.is_locked()
    if not locked:
        raise NotLocked("The page is not locked and thus can not be saved")
    self.full_clean()
    if not self.id:
        super().save(
            *args, **kwargs
        )  # Save a first time to correctly set _full_name
    # This reset the _full_name just before saving to maintain a coherent field quicker for queries than the
    # recursive method
    # It also update all the children to maintain correct names
    self._full_name = self.get_full_name()
    for c in self.children.all():
        c.save()
    super().save(*args, **kwargs)
    self.unset_lock()

get_page_by_full_name(name) staticmethod

Quicker to get a page with that method rather than building the request every time.

Source code in core/models.py
@staticmethod
def get_page_by_full_name(name):
    """Quicker to get a page with that method rather than building the request every time."""
    return Page.objects.filter(_full_name=name).first()

clean()

Cleans up only the name for the moment, but this can be used to make any treatment before saving the object.

Source code in core/models.py
def clean(self):
    """Cleans up only the name for the moment, but this can be used to make any treatment before saving the object."""
    if "/" in self.name:
        self.name = self.name.split("/")[-1]
    if (
        Page.objects.exclude(pk=self.pk)
        .filter(_full_name=self.get_full_name())
        .exists()
    ):
        raise ValidationError(_("Duplicate page"), code="duplicate")
    super().clean()
    if self.parent is not None and self in self.get_parent_list():
        raise ValidationError(_("Loop in page tree"), code="loop")

is_locked()

Is True if the page is locked, False otherwise.

This is where the timeout is handled, so a locked page for which the timeout is reach will be unlocked and this function will return False.

Source code in core/models.py
def is_locked(self):
    """Is True if the page is locked, False otherwise.

    This is where the timeout is handled,
    so a locked page for which the timeout is reach will be unlocked and this
    function will return False.
    """
    if self.lock_timeout and (
        timezone.now() - self.lock_timeout > timedelta(minutes=5)
    ):
        # print("Lock timed out")
        self.unset_lock()
    return (
        self.lock_user
        and self.lock_timeout
        and (timezone.now() - self.lock_timeout < timedelta(minutes=5))
    )

set_lock(user)

Sets a lock on the current page or raise an AlreadyLocked exception.

Source code in core/models.py
def set_lock(self, user):
    """Sets a lock on the current page or raise an AlreadyLocked exception."""
    if self.is_locked() and self.get_lock() != user:
        raise AlreadyLocked("The page is already locked by someone else")
    self.lock_user = user
    self.lock_timeout = timezone.now()
    super().save()

set_lock_recursive(user)

Locks recursively all the child pages for editing properties.

Source code in core/models.py
def set_lock_recursive(self, user):
    """Locks recursively all the child pages for editing properties."""
    for p in self.children.all():
        p.set_lock_recursive(user)
    self.set_lock(user)

unset_lock_recursive()

Unlocks recursively all the child pages.

Source code in core/models.py
def unset_lock_recursive(self):
    """Unlocks recursively all the child pages."""
    for p in self.children.all():
        p.unset_lock_recursive()
    self.unset_lock()

unset_lock()

Always try to unlock, even if there is no lock.

Source code in core/models.py
def unset_lock(self):
    """Always try to unlock, even if there is no lock."""
    self.lock_user = None
    self.lock_timeout = None
    super().save()

get_lock()

Returns the page's mutex containing the time and the user in a dict.

Source code in core/models.py
def get_lock(self):
    """Returns the page's mutex containing the time and the user in a dict."""
    if self.lock_user:
        return self.lock_user
    raise NotLocked("The page is not locked and thus can not return its user")

get_full_name()

Computes the real full_name of the page based on its name and its parent's name You can and must rely on this function when working on a page object that is not freshly fetched from the DB (For example when treating a Page object coming from a form).

Source code in core/models.py
def get_full_name(self):
    """Computes the real full_name of the page based on its name and its parent's name
    You can and must rely on this function when working on a page object that is not freshly fetched from the DB
    (For example when treating a Page object coming from a form).
    """
    if self.parent is None:
        return self.name
    return "/".join([self.parent.get_full_name(), self.name])

PageRev

Bases: Model

True content of the page.

Each page object has a revisions field that is a list of PageRev, ordered by date. my_page.revisions.last() gives the PageRev object that is the most up-to-date, and thus, is the real content of the page. The content is in PageRev.title and PageRev.content .

Notification

Bases: Model

Gift

Bases: Model

OperationLog

Bases: Model

General purpose log object to register operations.

validate_promo(value)

Source code in core/models.py
def validate_promo(value):
    start_year = settings.SITH_SCHOOL_START_YEAR
    delta = (date.today() + timedelta(days=180)).year - start_year
    if value < 0 or delta < value:
        raise ValidationError(
            _("%(value)s is not a valid promo (between 0 and %(end)s)"),
            params={"value": value, "end": delta},
        )

get_group(*, pk=None, name=None)

Search for a group by its primary key or its name. Either one of the two must be set.

The result is cached for the default duration (should be 5 minutes).

Parameters:

Name Type Description Default
pk int

The primary key of the group

None
name str

The name of the group

None

Returns:

Type Description
Optional[Group]

The group if it exists, else None

Raises:

Type Description
ValueError

If no group matches the criteria

Source code in core/models.py
def get_group(*, pk: int = None, name: str = None) -> Optional[Group]:
    """Search for a group by its primary key or its name.
    Either one of the two must be set.

    The result is cached for the default duration (should be 5 minutes).

    Args:
        pk: The primary key of the group
        name: The name of the group

    Returns:
        The group if it exists, else None

    Raises:
        ValueError: If no group matches the criteria
    """
    if pk is None and name is None:
        raise ValueError("Either pk or name must be set")

    # replace space characters to hide warnings with memcached backend
    pk_or_name: str | int = pk if pk is not None else name.replace(" ", "_")
    group = cache.get(f"sith_group_{pk_or_name}")

    if group == "not_found":
        # Using None as a cache value is a little bit tricky,
        # so we use a special string to represent None
        return None
    elif group is not None:
        return group
    # if this point is reached, the group is not in cache
    if pk is not None:
        group = Group.objects.filter(pk=pk).first()
    else:
        group = Group.objects.filter(name=name).first()
    if group is not None:
        cache.set(f"sith_group_{group.id}", group)
        cache.set(f"sith_group_{group.name.replace(' ', '_')}", group)
    else:
        cache.set(f"sith_group_{pk_or_name}", "not_found")
    return group

get_directory(instance, filename)

Source code in core/models.py
def get_directory(instance, filename):
    return ".{0}/{1}".format(instance.get_parent_path(), filename)

get_compressed_directory(instance, filename)

Source code in core/models.py
def get_compressed_directory(instance, filename):
    return "./.compressed/{0}/{1}".format(instance.get_parent_path(), filename)

get_thumbnail_directory(instance, filename)

Source code in core/models.py
def get_thumbnail_directory(instance, filename):
    return "./.thumbnails/{0}/{1}".format(instance.get_parent_path(), filename)

get_default_owner_group()

Source code in core/models.py
def get_default_owner_group():
    return settings.SITH_GROUP_ROOT_ID