Source code for superdjango.db.published.models

# Imports

from django.conf import settings
from django.db import models
from django.utils.timezone import now
from django.utils.translation import gettext_lazy as _
from superdjango.shortcuts import get_user_name
from ..audit.utils import is_audit_model

# Exports

__all__ = (
    "PublishedByModel",
)

# Constants

AUTH_USER_MODEL = settings.AUTH_USER_MODEL

# Models


[docs]class PublishedByModel(models.Model): """Represents a record (content of some sort) that may be published or unpublished. **Fields** The following fields are provided: - ``is_published`` - ``published_dt`` - ``published_by`` """ is_published = models.BooleanField( _("published"), default=False, help_text=_("Indicates the content is published.") ) published_by = models.ForeignKey( AUTH_USER_MODEL, blank=True, help_text=_("The user publishing the content."), null=True, on_delete=models.SET_NULL, related_name="%(app_label)s_%(class)s_published_records", verbose_name=_("published by") ) published_dt = models.DateTimeField( _("published date/time"), blank=True, help_text=_("Date and time the news item was published."), null=True ) class Meta: abstract = True
[docs] def mark_published(self, user, audit=True, commit=True): """Publish the content. :param user: The user publishing the content. :type user: AUTH_USER_MODEL :param audit: Call the ``audit()`` method if this is also an audit model. :type audit: bool :param commit: Indicates the record should be saved. :type commit: bool """ # Prevent update of published info. if not self.is_published: self.is_published = True self.published_by = user self.published_dt = now() if audit and is_audit_model(self): # noinspection PyUnresolvedReferences self.audit(user, commit=False) if commit: self.save()
[docs] def mark_unpublished(self, user, audit=True, commit=True): """Un-publish the content. :param user: The user publishing the content. :type user: AUTH_USER_MODEL :param audit: Call the ``audit()`` method if this is also an audit model. :type audit: bool :param commit: Indicates the record should be saved. :type commit: bool """ self.is_published = False self.published_by = None self.published_dt = None if audit and is_audit_model(self): # noinspection PyUnresolvedReferences self.audit(user, commit=False) if commit: self.save()
@property def published_by_name(self): """Get the full name or user name of the user that published the record. :rtype: str """ return get_user_name(self.published_by)