Database¶
A plethora, a cornucopia, a totally ridiculous number of models, fields, and other resources that may be used as a starting point for your database.
Version: 0.4.0-d
Name |
Version |
Stage |
Maintainer |
---|---|---|---|
archived |
0.10.0-d |
development |
Shawn Davis <shawn@superdjango.com> |
audit |
0.11.0-d |
development |
Shawn Davis <shawn@superdjango.com> |
calculated |
0.6.0-p |
planning |
Shawn Davis <shawn@superdjango.com> |
completed |
0.11.0-d |
development |
Shawn Davis <shawn@superdjango.com> |
datetime |
0.8.0-d |
development |
Shawn Davis <shawn@superdjango.com> |
default |
0.6.0-x |
experimental |
Shawn Davis <shawn@superdjango.com> |
displayed |
0.4.0-a |
alpha |
Shawn Davis <shawn@superdjango.com> |
eav |
0.6.0-x |
experimental |
Shawn Davis <shawn@superdjango.com> |
expiration |
0.7.0-p |
planning |
Shawn Davis <shawn@superdjango.com> |
history |
0.7.0-p |
planning |
Shawn Davis <shawn@superdjango.com> |
locked |
0.7.1-p |
planning |
Shawn Davis <shawn@superdjango.com> |
lookups |
0.9.0-d |
development |
Shawn Davis <shawn@superdjango.com> |
owned |
0.12.1-d |
development |
Shawn Davis <shawn@superdjango.com> |
parent |
0.7.0-x |
experimental |
Shawn Davis <shawn@superdjango.com> |
polymorphic |
0.4.0-x |
experimental |
Shawn Davis <shawn@superdjango.com> |
primary |
0.7.0-x |
experimental |
Shawn Davis <shawn@superdjango.com> |
published |
0.10.0-d |
development |
Shawn Davis <shawn@superdjango.com> |
random |
0.6.0-x |
experimental |
Shawn Davis <shawn@superdjango.com> |
resolved |
0.3.0-d |
development |
Shawn Davis <shawn@superdjango.com> |
reviewed |
0.3.0-d |
development |
Shawn Davis <shawn@superdjango.com> |
revised |
0.2.0-x |
experimental |
Shawn Davis <shawn@superdjango.com> |
slug |
0.4.0-x |
experimental |
Shawn Davis <shawn@superdjango.com> |
sorted |
0.7.0-x |
experimental |
Shawn Davis <shawn@superdjango.com> |
timed |
0.6.0-x |
experimental |
Shawn Davis <shawn@superdjango.com> |
trashed |
0.6.1-x |
experimental |
Shawn Davis <shawn@superdjango.com> |
utils |
0.1.0-x |
experimental |
Shawn Davis <shawn@superdjango.com> |
The resources provided by SuperDjango DB general consist of abstract models that may be used for various common (and some not so common) purposes.
Note
SuperDjango DB does not (and will never) provide concrete models.
Archived Models¶
Provides support for a simple archive workflow.
Component Reference: Archived Models
admin¶
-
class
superdjango.db.archived.admin.
BaseArchivedAdmin
(model, admin_site)[source]¶ Bases:
django.contrib.admin.options.ModelAdmin
Base admin class for models implementing the
ArchivedModel
.-
get_actions
(request)[source]¶ Return a dictionary mapping the names of all actions for this ModelAdmin to a tuple of (callable, name, description) for each action.
-
get_list_display
(request)[source]¶ Return a sequence containing the fields to be displayed on the changelist.
-
filters¶
Audit filters may be used in the Django Admin to create list filters using the full name of the user.
-
class
superdjango.db.archived.filters.
ArchivedByListFilter
(request, params, model, model_admin)[source]¶ Bases:
django.contrib.admin.filters.SimpleListFilter
Filter for
archived_by
.Order By
Ordering for the lookup defaults to
USERNAME_FIELD
. You can change this by settingSUPERDJANGO_ORDER_USERS_BY
in yoursettings.py
file.
managers¶
models¶
-
class
superdjango.db.archived.models.
ArchivedModel
(*args, **kwargs)[source]¶ Bases:
django.db.models.base.Model
Supports records that may be archived.
Fields
archived_by
archived_dt
is_archived
Proper Name
The
archived_by_name
property is also provided which attempts to return the full name of the user.Methods
mark_archived()
mark_unarchived()
- Parameters
cached_archived_by_name (CharField) – The name of the person that archived the record.
archived_by_id (ForeignKey) – The user that archived the record.
archived_dt (DateTimeField) – Date and time the record was archived.
is_archived (BooleanField) – Indicates the record is archived.
-
property
archived_by_name
¶ Get the name of the user that archived the record.
- Return type
str | None
-
mark_archived
(user, audit=True, commit=True)[source]¶ Mark the record as archived.
- Parameters
user (AUTH_USER_MODEL) – The user marking the record as archived.
audit (bool) – Call the
audit()
method if this is also an audit model.commit (bool) – Whether to save immediately.
Note
Mark archived changes the record only if
archived_dt
isNone
. This prevents updating the user or date/time ifmark_archived()
is called more than once.
Audit Models¶
Adds support for added by/modified by/viewed by (and added/modified/viewed date/time) to a model.
Component Reference: Audit Models
mixins¶
-
class
superdjango.db.audit.mixins.
AuditMixin
(*args, **kwargs)[source]¶ Bases:
django.db.models.base.Model
Base for other abstract auditing models.
The class serves two purposes:
Provide a centralized
audit()
method that child classes may call to save audit data.Act as a flag for the
is_audit_model()
function to indicate the presence of audit functionality.
models¶
-
class
superdjango.db.audit.models.
AddedByModel
(*args, **kwargs)[source]¶ Bases:
superdjango.db.audit.mixins.AuditMixin
,django.db.models.base.Model
Tracks the user that added a record as well as the date and time the record was created.
Fields
This class will add the following fields:
added_by
The user that added the record.added_dt
The date and time the record was added.
Proper Name
The
added_by_name
property is also provided which attempts to return the full name of the user.Implementation
class Project(AddedByModel): # ... class Meta: get_latest_by = "added_dt" ordering = ["-added_dt"]
- Parameters
added_by_id (ForeignKey) – Added by
added_dt (AutoNowAddDateTimeField) – Date and time the record was created.
-
property
added_by_name
¶ Get the full name or user name of the user that added the record.
- Return type
str
-
class
superdjango.db.audit.models.
ModifiedByModel
(*args, **kwargs)[source]¶ Bases:
superdjango.db.audit.mixins.AuditMixin
Tracks the user that last updated a record as well as the date and time of the last update.
Fields
This class will add the following fields:
modified_by
The user that modified record.modified_dt
The date and time the modified was added.
Proper Name
The
modified_by_name
property is also provided which attempts to return the full name of the user.Implementation
class MyModel(ModifiedByModel): # ... class Meta: ordering = ["modified_dt"]
- Parameters
modified_by_id (ForeignKey) – Modified by
modified_dt (AutoNowDateTimeField) – Date and time the record was last modified.
-
property
modified_by_name
¶ Get the full name or user name of the user that last modified the record.
- Return type
str
-
class
superdjango.db.audit.models.
ViewedByModel
(*args, **kwargs)[source]¶ Bases:
superdjango.db.audit.mixins.AuditMixin
Tracks the user that view a record as well as the date and time the record was last viewed.
Fields
This class will add the following fields:
viewed_by
The user that viewed record.viewed_dt
The date and time the record was last viewed.
Proper Name
The
viewed_by_name
property is also provided which attempts to return the full name of the user.Implementation
class MedicalRecord(ViewedByModel): # ...
- Parameters
viewed_by_id (ForeignKey) – Viewed by
viewed_dt (DateTimeField) – Date and time the record was last viewed.
-
audit
(user, commit=True)[source]¶ Update viewed fields.
Important
This method makes calls to
super()
which may also trigger the update of other fields if the model also extendsAddedByModel
orModifiedByModel
. Seemark_viewed()
if you just want to update theviewed_by
andviewed_dt
fields.
-
mark_unviewed
(commit=True)[source]¶ Mark the record as “un-viewed”, removing the last viewed data.
- Parameters
commit (bool) – Indicates the record should be saved after updating the field.
-
mark_viewed
(user, commit=True)[source]¶ Mark the record as viewed.
- Parameters
user (AUTH_USER_MODEL) – The user that reviewed the record.
commit (bool) – Indicates the record should be saved after updating the field.
-
property
viewed_by_name
¶ Get the full name or user name of the user that last viewed the record.
- Return type
str
admin¶
filters¶
Audit filters may be used in the Django Admin to create list filters using the full name of the user.
-
class
superdjango.db.audit.filters.
AddedByListFilter
(request, params, model, model_admin)[source]¶ Bases:
superdjango.db.audit.filters.BaseAuditListFilter
Filter for
added_by
.
-
class
superdjango.db.audit.filters.
BaseAuditListFilter
(request, params, model, model_admin)[source]¶ Bases:
django.contrib.admin.filters.SimpleListFilter
Base class for creating list filters based on user audit fields.
Order By
Ordering for the lookup defaults to
USERNAME_FIELD
. You can change this by settingSUPERDJANGO_ORDER_USERS_BY
in yoursettings.py
file.Implementation
When extending, set the
parameter_name
to the name of the audit field.
-
class
superdjango.db.audit.filters.
ModifiedByListFilter
(request, params, model, model_admin)[source]¶ Bases:
superdjango.db.audit.filters.BaseAuditListFilter
Filter for
modified_by
.
-
class
superdjango.db.audit.filters.
ViewedByListFilter
(request, params, model, model_admin)[source]¶ Bases:
superdjango.db.audit.filters.BaseAuditListFilter
Filter for
viewed_by
.
Calculated Fields¶
Provides support for standard calculated fields as well as creating your own calculated fields.
Component Reference: Calculated Fields
fields¶
-
class
superdjango.db.calculated.fields.
CalculatedFieldMixin
(**kwargs)[source]¶ Bases:
object
Mixin for automatically calculate the value of the field from two or more other integer fields.
-
__init__
(**kwargs)[source]¶ Initialize the field.
- Parameters
calculate_from (list) – A list of field names upon which the calculation is based.
calculate_type (str | callable) – The type of calculation to perform; one of
avg
,max
,``min`` ortotal
. A callable may also be given. Defaults tototal
.
If a callable is provided for``calculate_type``, it must accept a dictionary of field name field value pairs to be calculated. It must also return a value of the appropriate type.
During init, the
check_calculation_type()
method is automatically called. You may need to override this if custom validation of thecalculate_type
is needed.Note
Calculated fields are not editable.
Init will raise the following errors:
ImproperlyConfigured
when nocalculate_from
is provided.ValueError
if thecalculate_from
is not given as a list or tuple.ImproperlyConfigured
whencheck_calculation_type()
fails.
-
check_calculation_type
()[source]¶ Check that the given calculation type is supported.
- Return type
bool
-
-
class
superdjango.db.calculated.fields.
CalculatedFloatField
(**kwargs)[source]¶ Bases:
superdjango.db.calculated.fields.CalculatedFieldMixin
,django.db.models.fields.FloatField
Automatically calculate the value of the field from two or more other integer fields.
-
class
superdjango.db.calculated.fields.
CalculatedIntegerField
(**kwargs)[source]¶ Bases:
superdjango.db.calculated.fields.CalculatedFieldMixin
,django.db.models.fields.IntegerField
Automatically calculate the value of the field from two or more other integer fields.
from superdjango.db.calculated.fields import CalculatedIntegerField class Task(models.Model): pessimistic_estimate = models.IntegerField() optimistic_estimate = models.IntegerField() realistic_estimate = models.IntegerField() average_estimate = CalculatedIntegerField( _("average estimate"), calculate_from=[ "pessimistic_estimate", "optimistic_estimate", "realistic_estimate", ], calculate_type=CalculatedIntegerField.AVERAGE )
-
class
superdjango.db.calculated.fields.
ConcatenatedCharField
(**kwargs)[source]¶ Bases:
superdjango.db.calculated.fields.CalculatedFieldMixin
,django.db.models.fields.CharField
Concatenate char fields together.
Completed Models¶
Provides the ability to mark a record as complete.
Component Reference: Completed Models
admin¶
-
class
superdjango.db.completed.admin.
BaseCompletedByAdmin
(model, admin_site)[source]¶ Bases:
django.contrib.admin.options.ModelAdmin
Base admin class for models implementing the
CompletedByModel
.-
get_actions
(request)[source]¶ Return a dictionary mapping the names of all actions for this ModelAdmin to a tuple of (callable, name, description) for each action.
-
get_list_display
(request)[source]¶ Return a sequence containing the fields to be displayed on the changelist.
-
filters¶
Audit filters may be used in the Django Admin to create list filters using the full name of the user.
-
class
superdjango.db.completed.filters.
CompletedByListFilter
(request, params, model, model_admin)[source]¶ Bases:
django.contrib.admin.filters.SimpleListFilter
Filter for
completed_by
.Order By
Ordering for the lookup defaults to
USERNAME_FIELD
. You can change this by settingSUPERDJANGO_ORDER_USERS_BY
in yoursettings.py
file.Implementation
When extending, set the
parameter_name
to the name of the audit field.
managers¶
models¶
-
class
superdjango.db.completed.models.
CompletedByModel
(*args, **kwargs)[source]¶ Bases:
django.db.models.base.Model
Tracks the user that marked a record as complete as well as the date and time the record was marked complete.
Completed may mean different things in different contexts. It just depends on your app.
Fields
This class will add the following fields:
cached_completed_by_name
: Since the user is nullable, this captures the name of the user.completed_by
: The user that completed the record.completed_dt
: The date and time the record was completed.is_complete
: A boolean flag.
Methods
Conveniences methods have also been added for working with records.
mark_complete()
mark_incomplete()
toggle_complete()
Implementation
class Task(CompletedByModel): # ... class Meta: ordering = ["completed_dt"]
- Parameters
cached_completed_by_name (CharField) – the name of the person that marked the record complete.
completed_by_id (ForeignKey) – Person that marked this complete.
completed_dt (DateTimeField) – Date and time of completion.
is_complete (BooleanField) – Indicates this is complete.
-
property
completed_by_name
¶ Alias for
cached_completed_by_name
.
-
mark_complete
(user, commit=True)[source]¶ Mark the record as complete.
- Parameters
user (AUTH_USER_MODEL) – The user marking the record as complete.
commit (bool) – Save the record after marking it as complete.
Note
Mark complete changes the record only if
completed_dt
isNone
. This prevents updating the user or date/time ifmark_complete()
is called more than once.
Date/Time Models¶
Fields and abstract models for working with dates and datetimes.
Component Reference: Date/Time Models
fields¶
-
class
superdjango.db.datetime.fields.
AutoNowAddDateTimeField
(*args, **kwargs)[source]¶ Bases:
django.db.models.fields.DateTimeField
Automatically sets the date/time to “now” when the record is created.
It uses Django’s timezone utils, which returns an aware or naive datetime, depending on
settings.USE_TZ
. However, use ofUSE_TZ
is strongly recommended and is the default for new Django projects.The
editable
field is also set toFalse
by default.
-
class
superdjango.db.datetime.fields.
AutoNowDateTimeField
(*args, **kwargs)[source]¶ Bases:
superdjango.db.datetime.fields.AutoNowAddDateTimeField
Extends
AutoNowAddField
to also add the current date/time whenever the record is saved.
models¶
-
class
superdjango.db.datetime.models.
TimeStampedModel
(*args, **kwargs)[source]¶ Bases:
django.db.models.base.Model
A base model for creating a record that includes added and modified datetime stamps.
Fields
added_dt
: The date and time the record was created.modified_dt
: The date and time the record was last modified.
- Parameters
added_dt (AutoNowAddDateTimeField) – Date and time the record was created.
modified_dt (AutoNowDateTimeField) – Date and time the record was last modified.
Default Models¶
Provides the ability to mark a record as the default of it’s type.
Component Reference: Default Models
admin¶
managers¶
-
class
superdjango.db.default.managers.
DefaultManager
(*args, **kwargs)[source]¶ Bases:
django.db.models.manager.Manager
Supports the
DefaultModel
.from superdjango.db.default.managers import DefaultManager from superdjango.db.default.models import DefaultModel class Currency(DefaultModel): code = models.CharField(max_length=4) name = models.CharField(max_length=64) default_currency = Currency.objects.default()
mixins¶
-
class
superdjango.db.default.mixins.
DefaultMixin
(*args, **kwargs)[source]¶ Bases:
django.db.models.base.Model
Base class for implementing a “default” model.
This model supplies the methods for using the
pre_save
signal and to acquire the name of the field that provides the default flag.-
static
allow_one_default
(sender, **kwargs)[source]¶ Use this when there can be only one
is_default
that isTrue
.
-
classmethod
get_default_flag_name
()[source]¶ Get the name of the field that is used to mark the record as default.
- Return type
str
-
static
models¶
-
class
superdjango.db.default.models.
DefaultModel
(*args, **kwargs)[source]¶ Bases:
superdjango.db.default.mixins.DefaultMixin
Allows a record to be marked as “default”.
This model is an implementation of :py:class`superdjango.db.default.mixins.DefaultMixin`, providing an
is_default
field.- Parameters
is_default (NullBooleanField) – Indicates that this is the default record.
Displayed Models¶
Provides a consistent means of acquiring the human friendly name of a model instance.
Component Reference: Displayed Models
mixins¶
-
class
superdjango.db.displayed.mixins.
DisplayNameMixin
[source]¶ Bases:
object
Implement consistent proper naming for models that extend this class.
models¶
-
class
superdjango.db.displayed.models.
DisplayNameModel
(*args, **kwargs)[source]¶ Bases:
superdjango.db.displayed.mixins.DisplayNameMixin
,django.db.models.base.Model
Extend
DisplayNameMixin
to also cache the display name.- Parameters
cached_choice_name (CharField) – The proper name of the record when used as a choice.
cached_display_name (CharField) – The proper name of the record.
-
property
choice_name
¶ Get the cached name or the current name.
- Return type
str
-
property
display_name
¶ Get the cached name or the current name.
- Return type
str
EAV Models¶
Support for the Entity Attribute Value (EAV) approach to adding custom fields.
Component Reference: EAV Models
admin¶
-
class
superdjango.db.eav.admin.
BaseAttributeModelAdmin
(model, admin_site)[source]¶ Bases:
django.contrib.admin.options.ModelAdmin
Base admin for an attribute model.
constants¶
mappings¶
-
superdjango.db.eav.mappings.
CUSTOM_FIELD_MAPPINGS
= {'boolean': <class 'django.forms.fields.BooleanField'>, 'date': <class 'django.forms.fields.DateField'>, 'datetime': <class 'django.forms.fields.DateTimeField'>, 'decimal': <class 'django.forms.fields.DecimalField'>, 'duration': <class 'django.forms.fields.DurationField'>, 'email': <class 'django.forms.fields.EmailField'>, 'float': <class 'django.forms.fields.FloatField'>, 'integer': <class 'django.forms.fields.IntegerField'>, 'ip': <class 'django.forms.fields.GenericIPAddressField'>, 'list': <class 'django.forms.fields.ChoiceField'>, 'slug': <class 'django.forms.fields.SlugField'>, 'text': <class 'django.forms.fields.CharField'>, 'time': <class 'django.forms.fields.TimeField'>, 'url': <class 'django.forms.fields.URLField'>, 'varchar': <class 'django.forms.fields.CharField'>}¶ Map EAV data types to form fields.
models¶
-
class
superdjango.db.eav.models.
AttributeModel
(*args, **kwargs)[source]¶ Bases:
django.db.models.base.Model
Base model for implementing extra attributes to be associated with a model.
- Parameters
choices (TextField) – Used for the list data type. One choice per line.
content_type_id (ForeignKey) – Prompt the user to choose options from the selected content type.
decimal_places (PositiveSmallIntegerField) – Decimal places for decimal fields.
data_type (CharField) – Data type
grouping (CharField) – The fieldset or tab into which the field is organized.
help_text (TextField) – Help displayed to the user regarding the attribute.
is_enabled (BooleanField) – Indicates the attribute is available for use.
is_hidden (NullBooleanField) – Use this to hide options that are not configurable by the user. Be sure to specify a default.
is_required (BooleanField) – Make input for this attribute required. Be careful!
label (CharField) – A label or title of the attribute.
limit_choices_to (CharField) – A filter statement in JSON format that may be used to limit content type choices.
max_digits (PositiveSmallIntegerField) – Max number of digits for decimal fields.
max_length (PositiveSmallIntegerField) – Max number of characters for single-line text.
min_length (PositiveSmallIntegerField) – Minimum number of characters for single-line text.
name (CharField) – The name may be used as an identifier in reports, exports, and customizations.
raw_default_value (CharField) – The default value, if any. However, it is recommended that all attributes have a default.
sort_order (SmallIntegerField) – Sort order
-
clean
()[source]¶ Make sure choices or content type has been provided for
DATA_TYPE.LIST
. Hidden values also require a default.
-
property
default_value
¶ Alias for
get_default()
.
-
get_default
()[source]¶ Get the default value based on
data_type
.- Return type
int | float | str | None
-
property
has_choices
¶ Indicates whether choices have been defined for the value.
- Return type
bool
-
property
value
¶ Always returns the value of
get_default()
. Conforms to the API forValueModel
.
-
class
superdjango.db.eav.models.
ValueModel
(*args, **kwargs)[source]¶ Bases:
django.db.models.base.Model
Base class for specifying the value of an attribute.
You must define the attribute foreign key as well as a foreign key to the model to which this value is added.:
from superdjango.db.eav.models import AttributeModel, ValueModel class Profile(models.Model): # ... class ExtraAttribute(AttributeModel): # ... class ExtraAttributeValue(ValueModel): attribute = models.ForeignKey( ExtraAttribute, related_name="values" ) profile = models.ForeignKey( Profile, related_name="attributes" ) def get_attribute(self): return self.attribute
- Parameters
raw_value (TextField) – Value
-
property
choices
¶ Alias for
get_choices()
.
-
property
data_type
¶ Alias for the attribute’s
data_type
.
-
property
decimal_places
¶ Alias for the attribute’s
decimal_places
.
-
display_value
()[source]¶ Display the human-friendly value the attribute.
- Return type
float | int | str
-
get_attribute
()[source]¶ Get the attribute instance.
- Return type
BaseType[AttributeModel]
-
get_content_object
()[source]¶ Get the content object associated with the value when a content type is used.
-
property
help_text
¶ Alias for the attribute’s
help_text
.
-
property
is_required
¶ Alias for the attribute’s
is_required
.
-
property
label
¶ Alias for the attribute’s
label
.
-
property
max_digits
¶ Alias for the attribute’s
max_digits
.
-
property
max_length
¶ Alias for the attribute’s
max_length
.
-
property
min_length
¶ Alias for the attribute’s
min_length
.
-
property
name
¶ Alias for the attribute’s
name
.
-
property
sort_order
¶ Alias for the attribute’s
sort_order
.
-
property
value
¶ Alias for
get_value()
.
ui¶
-
class
superdjango.db.eav.ui.
BaseAttributeInlineModelUI
(parent_model, current_site=None)[source]¶ Bases:
superdjango.ui.options.interfaces.InlineModelUI
Base inline for including attributes fields.
-
class
superdjango.db.eav.ui.
BaseAttributeModelUI
(site=None)[source]¶ Bases:
superdjango.ui.options.interfaces.ModelUI
Base UI for an attribute model.
Expiration Models¶
Work with records that have an expiration date and time.
Component Reference: Expiration Models
managers¶
-
class
superdjango.db.expiration.managers.
ExpirationManager
(*args, **kwargs)[source]¶ Bases:
django.db.models.manager.Manager
Works in conjunction with
ExpirationModel
to filter by expiration.
-
class
superdjango.db.expiration.managers.
ExpirationQuerySet
(model=None, query=None, using=None, hints=None)[source]¶ Bases:
django.db.models.query.QuerySet
Works in conjunction with
ExpirationModel
to help filter out records that have expired.
models¶
-
class
superdjango.db.expiration.models.
ExpirationModel
(*args, **kwargs)[source]¶ Bases:
django.db.models.base.Model
Allows a model to (semi) automatically expire.
Note
There are several options for managers. It is left to the developer to decide which ones are needed.
- Parameters
expiration_dt (DateTimeField) – Date and time the record should expire.
has_expired (BooleanField) – Indicates the record has expired.
History Models¶
Abstract model for implementing audit history on models.
Component Reference: History Models
admin¶
-
class
superdjango.db.history.admin.
BaseHistoryModelAdmin
(model, admin_site)[source]¶ Bases:
django.contrib.admin.options.ModelAdmin
Base class for history admin.
-
get_list_display
(request)[source]¶ Return a sequence containing the fields to be displayed on the changelist.
-
get_list_filter
(request)[source]¶ Return a sequence containing the fields to be displayed as filters in the right sidebar of the changelist page.
-
has_add_permission
(request)[source]¶ Return True if the given request has permission to add an object. Can be overridden by the user in subclasses.
-
has_delete_permission
(request, obj=None)[source]¶ Return True if the given request has permission to change the given Django model instance, the default implementation doesn’t examine the obj parameter.
Can be overridden by the user in subclasses. In such case it should return True if the given request has permission to delete the obj model instance. If obj is None, this should return True if the given request has permission to delete any object of the given type.
-
constants¶
-
superdjango.db.history.constants.
CREATE_VERBS
= ('add', 'added', 'create', 'created', 'new')¶ A list of recognized record creation verbs.
-
superdjango.db.history.constants.
DELETE_VERBS
= ('delete', 'deleted', 'remove', 'removed')¶ A list of recognized record deletion verbs.
-
superdjango.db.history.constants.
DETAIL_VERBS
= ('detail', 'view', 'viewed')¶ A list of recognized record detail verbs.
-
superdjango.db.history.constants.
UPDATE_VERBS
= ('change', 'changed', 'edit', 'edited', 'update', 'updated')¶ A list of recognized record update verbs.
models¶
-
class
superdjango.db.history.models.
HistoryModel
(*args, **kwargs)[source]¶ Bases:
django.db.models.base.Model
An abstract model for implementing a running record history.
from superdjango.db.history.models import HistoryModel class LogEntry(HistoryModel): class Meta: get_latest_by = "added_dt" ordering = ["-added_dt"] verbose_name = _("Log Entry") verbose_name_plural = _("Log Entries")
- Parameters
absolute_url (CharField) – The URL of the model instance.
added_dt (DateTimeField) – Date and time the action was taken.
content_type_id (ForeignKey) – The internal content type of the object.
object_id (CharField) – The object (record) ID.
object_label (CharField) – The string representation of the object, i.e. it’s title, label, etc.
user_id (ForeignKey) – The user that performed the action.
user_name (CharField) – The name of the user that performed the action.
verb (CharField) – The verb (action) taken on a record.
verb_display (CharField) – The display value of the verb.
verbose_name (CharField) – The verbose name of the model.
-
property
action
¶ An alias for
get_verb_display()
.
-
classmethod
get_for
(record, limit=10)[source]¶ Get history entries for a given record.
- Parameters
record – The record (model instance) for which history is to be acquired.
limit (int) – The max number of history records to return.
- Return type
django.db.models.QuerySet
-
get_message
()[source]¶ Get the message that describes the action.
- Return type
str
Note
The added date/time of the entry is not localized for the current user’s timezone. To support this, you’ll need to implement the message in a template.
-
get_object
()[source]¶ Get the model instance that was the subject of the entry.
- Returns
The model instance. If the object was deleted,
None
is returned.
-
get_url
()[source]¶ Get the URL of the model instance.
The URL may not be available. Additionally, if the action represents a delete, no URL is returned.
- Return type
str | None
-
property
is_create
¶ Indicates the action is an addition.
- Return type
bool
-
property
is_delete
¶ Indicates the action is a delete.
- Return type
bool
-
property
is_detail
¶ Indicates the action is a detail.
- Return type
bool
-
property
is_update
¶ Indicates the action was an update.
- Return type
bool
-
classmethod
log
(record, user, verb, fields=None, url=None, verb_display=None)[source]¶ Create a new history entry.
- Parameters
record – The model instance.
user – The user (instance) performing the action.
verb (str) – The action taken.
fields (list[superdjango.db.history.utils.FieldChange]) – A list of changed fields.
url (str) – The URL of the model instance. Typically that of the detail view. If omitted, an attempt will be made to acquire the URL from
get_absolute_url()
.verb_display (str) – The human0friendly name of the action taken.
- Returns
The log entry instance.
Note
By default, nothing is done with
fields
. When you extend the class, you may save the fields to the extending model, or iterate over them to save each change to a separate model that refers back to the new history instance. Seelog_field_changes()
.
-
classmethod
log_field_changes
(instance, verb, fields=None)[source]¶ Log changes to fields.
- Parameters
instance – The history record, NOT the original model instance.
verb (str) – The action taken. This allows verbs such as create or delete to be ignored.
fields (list[superdjango.db.history.utils.FieldChange]) – A list of changed fields.
-
property
message
¶ An alias for
get_message()
.
-
property
performed_by
¶ Get the name of the user that performed the action.
- Return type
str
ui¶
-
class
superdjango.db.history.ui.
BaseHistoryModelUI
(site=None)[source]¶ Bases:
superdjango.ui.options.interfaces.ModelUI
Base class for UI based on
HistoryModel
.
utils¶
-
class
superdjango.db.history.utils.
FieldChange
(field_name, new_value, old_value, label=None)[source]¶ Bases:
object
Wraps the change that has occurred to a given field.
-
__init__
(field_name, new_value, old_value, label=None)[source]¶ Initialize a field change.
- Parameters
field_name (str) – The name of the field that was changed.
new_value – The new value, e.g. from the cleaned data of a form.
old_value – The existing value from the database prior to save.
label (str) – The field label (verbose name).
-
-
superdjango.db.history.utils.
get_field_changes
(form, model, record=None)[source]¶ Get the changed fields for a given form and record.
- Parameters
form – The validated form instance.
model – The model class represented by the record.
record – The current record instance. It is safe to pass
None
.
- Return type
- Returns
A list pf changed fields when record is not
None
. Otherwise, an empty list.
Locked Models¶
Work with records that have been locked from update or delete.
Component Reference: Locked Models
admin¶
-
class
superdjango.db.locked.admin.
BaseLockedModelAdmin
(model, admin_site)[source]¶ Bases:
django.contrib.admin.options.ModelAdmin
Add support for
superdjango.db.locked.models.LockedModel
.Inspired by this SO question on disabling the delete link in the admin.
-
get_fields
(request, obj=None)[source]¶ Add lock fields to the form. Override this to add your own fields or to remove these fields from the form.
-
get_list_display
(request)[source]¶ Add lock fields to the display. Override this to add your own fields or to remove these fields from the list.
-
has_change_permission
(request, obj=None)[source]¶ A record that is locked will suspend update permission.
Note
Super users always have the ability to change (and therefore lock/unlock) a record.
-
managers¶
models¶
-
class
superdjango.db.locked.models.
LockedModel
(*args, **kwargs)[source]¶ Bases:
django.db.models.base.Model
A model that prevents itself from being deleted or updated.
- Parameters
is_locked (NullBooleanField) – Indicates this record should not be deleted.
locked_by_id (ForeignKey) – The user that locked the record.
locked_dt (DateTimeField) – Date and time the record was locked.
Lookup Models¶
Provides pre-defined models for managing lookup (aka validation) data.
Component Reference: Lookup Models
admin¶
-
class
superdjango.db.lookups.admin.
BaseLookupAdmin
(model, admin_site)[source]¶ Bases:
django.contrib.admin.options.ModelAdmin
Base class for creating Django admin models for lookups.
-
get_list_display
(request)[source]¶ Return a sequence containing the fields to be displayed on the changelist.
-
models¶
-
class
superdjango.db.lookups.models.
IntegerLookupModel
(*args, **kwargs)[source]¶ Bases:
superdjango.db.lookups.models.LookupModel
Create a lookup with an integer value.
- Parameters
abbr (CharField) – Enter the common abbreviation for the entry, if any.
description (TextField) – Brief description of the entry.
is_enabled (BooleanField) – Indicates the lookup is enabled for use.
label (CharField) – Official name or title for the entry.
value (IntegerField) – The value of the lookup.
-
class
superdjango.db.lookups.models.
LookupModel
(*args, **kwargs)[source]¶ Bases:
django.db.models.base.Model
Base class for lookup models.
- Parameters
abbr (CharField) – Enter the common abbreviation for the entry, if any.
description (TextField) – Brief description of the entry.
is_enabled (BooleanField) – Indicates the lookup is enabled for use.
label (CharField) – Official name or title for the entry.
-
class
superdjango.db.lookups.models.
StringLookupModel
(*args, **kwargs)[source]¶ Bases:
superdjango.db.lookups.models.LookupModel
Create a lookup with a string value.
- Parameters
abbr (CharField) – Enter the common abbreviation for the entry, if any.
description (TextField) – Brief description of the entry.
is_enabled (BooleanField) – Indicates the lookup is enabled for use.
label (CharField) – Official name or title for the entry.
value (CharField) – The value of the lookup.
Owned Models¶
Provides a random character field.
Component Reference: Owned Models
admin¶
-
class
superdjango.db.owned.admin.
BaseOwnedByAdmin
(model, admin_site)[source]¶ Bases:
django.contrib.admin.options.ModelAdmin
Base admin class for models implementing the
OwnedByModel
.-
get_actions
(request)[source]¶ Return a dictionary mapping the names of all actions for this ModelAdmin to a tuple of (callable, name, description) for each action.
-
get_list_display
(request)[source]¶ Return a sequence containing the fields to be displayed on the changelist.
-
filters¶
Audit filters may be used in the Django Admin to create list filters using the full name of the user.
-
class
superdjango.db.owned.filters.
OwnedByListFilter
(request, params, model, model_admin)[source]¶ Bases:
django.contrib.admin.filters.SimpleListFilter
Filter for
owned_by
.Order By
Ordering for the lookup defaults to
first_name
. You can change this by settingSUPERDJANGO_ORDER_USERS_BY
in yoursettings.py
file.Implementation
When extending, set the
parameter_name
to the name of the audit field.
managers¶
models¶
-
class
superdjango.db.owned.models.
OwnedByModel
(*args, **kwargs)[source]¶ Bases:
django.db.models.base.Model
Identifies a user that owners the record, as distinct from the user that creates or modifies the record.
Fields
This class will add the following fields:
owned_by
The user that owns the record.
Implementation
class Business(OwnedByModel): # ...
- Parameters
owned_by_id (ForeignKey) – Select the user that owns the record.
Parent-Tree Models¶
Provides a simple model for implementing parent-child-sibling relationships.
Component Reference: Parent-Tree Models
models¶
-
class
superdjango.db.parent.models.
ParentTreeModel
(*args, **kwargs)[source]¶ Bases:
django.db.models.base.Model
A simple implementation of tree-like functionality using only a
parent
field that refers toself
.Note that some methods will be horribly inefficient, yet effective at finding all of the records associated with the current instance. If performance is a concern, then you may wish to review the following resources:
- Parameters
cached_level (PositiveSmallIntegerField) – Level
parent_id (ForeignKey) – Parent
-
get_ancestors
()[source]¶ Get the parent, grandparent, etc. for the current record.
- Return type
list
Note
The list is populated from nearest ancestor to furthest ancestor. Use
reversed()
as needed to re-order the list so that the top-most ancestor is first.
-
get_children
()[source]¶ Get the child records that are directly connected to the current record.
- Return type
django.db.models.QuerySet
-
get_descendants
()[source]¶ Get all of the descendants (children, grandchildren, etc.) for this record.
- Return type
list
-
get_level
(cached=True)[source]¶ Get the level of the record within the hierarchy.
- Parameters
cached (bool) – Indicates whether cache should be used.
- Return type
int
-
get_siblings
()[source]¶ Get the records that are directly connected to the record’s parent.
- Return type
django.db.models.QuerySet | None
-
has_children
()[source]¶ Indicates whether the record has child records associated with it.
- Return type
bool
-
has_siblings
()[source]¶ Indicates whether this record’s parent has other child records.
- Return type
bool
-
property
level
¶ An alias of
get_level()
.
utils¶
-
class
superdjango.db.parent.utils.
Diagram
(record)[source]¶ Bases:
object
Utility for graphing a parent-tree model instance.
-
static
get_color
(instance)[source]¶ Get the color to use for a record.
- Parameters
instance – The model instance.
- Return type
str
-
static
get_display_name
(instance)[source]¶ Get the human-friendly name of a record.
- Parameters
instance – The model instance.
- Return type
str
-
static
Polymorphic Models¶
Managers and mixins for polymorphic behavior.
Component Reference: Polymorphic Models
managers¶
This code was copied and adapted from django-model-utils, and originally contributed to that package by Jeff Elmore.
The original license is preserved below:
Copyright (c) 2009-2019, Carl Meyer and contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the author nor the names of other
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
models¶
-
class
superdjango.db.polymorphic.models.
PolymorphicMixin
(*args, **kwargs)[source]¶ Bases:
django.db.models.base.Model
A mixin for models that extend a polymorphic model.
The purpose of which is to provide a means of acquiring the pointer field that refers back to the parent model.
Primary Models¶
Provides support for a publishing workflow.
Component Reference: Primary Models
admin¶
managers¶
-
class
superdjango.db.primary.managers.
PrimaryManager
(*args, **kwargs)[source]¶ Bases:
django.db.models.manager.Manager
Supports the
PrimaryModel
.from superdjango.db.primary.managers import PrimaryManager from superdjango.db.primary.models import PrimaryModel class EmergencyContact(PrimaryModel): employee = models.ForeignKey(Employee, related_name="emergency_contacts") # ... employee = Employee.objects.get(pk=1) contact = employee.emergency_contacts.primary()
mixins¶
-
class
superdjango.db.primary.mixins.
PrimaryMixin
(*args, **kwargs)[source]¶ Bases:
django.db.models.base.Model
Base class for implementing a “primary” model.
This model supplies the methods for using the
pre_save
signal and to acquire the name of the field that provides the primary flag.-
static
allow_one_primary
(sender, **kwargs)[source]¶ Use this when there can be only one
is_primary
that isTrue
. Seeallow_one_default
for implementation example.
-
static
models¶
-
class
superdjango.db.primary.models.
PrimaryModel
(*args, **kwargs)[source]¶ Bases:
superdjango.db.primary.mixins.PrimaryMixin
Allows a record to be marked as “primary”.
This model supplies the following:
A
NullBooleanField
calledis_primary
.Two static methods for use with the
pre_save
signal:allow_one_primary()
andrequire_one_primary()
.
# models.py from django.db import models from superdjango.db.primary.models import PrimaryModel class Address(models.Model): # A contact's address. class Contact(models.Model): # A contact in an address book. class LinkContactAddress(PrimaryModel): # Connect contacts with addresses. address = models.ForeignKey(Address) contact = models.ForeignKey(Contact) # receivers.py from django.db.models.signals import pre_save from .models import LinkContactAddress pre_save.connect( LinkContactAddress.allow_one_primary, LinkContactAddress, dispath_uid="linkcontactaddress_allow_one_primary" ) # Or to require a primary record. pre_save.connect( LinkContactAddress.require_one_primary, LinkContactAddress, dispath_uid="linkcontactaddress_require_one_primary" )
- Parameters
is_primary (NullBooleanField) – Indicates that this is the primary record.
Published Models¶
Provides support for a publishing workflow.
Component Reference: Published Models
admin¶
-
class
superdjango.db.published.admin.
BasePublishedByModelAdmin
(model, admin_site)[source]¶ Bases:
django.contrib.admin.options.ModelAdmin
Base admin class for models implementing the
PublishedByModel
.
filters¶
-
class
superdjango.db.published.filters.
PublishedByListFilter
(request, params, model, model_admin)[source]¶ Bases:
superdjango.db.audit.filters.BaseAuditListFilter
Filter for
published_by
.
models¶
-
class
superdjango.db.published.models.
PublishedByModel
(*args, **kwargs)[source]¶ Bases:
django.db.models.base.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
- Parameters
is_published (BooleanField) – Indicates the content is published.
published_by_id (ForeignKey) – The user publishing the content.
published_dt (DateTimeField) – Date and time the news item was published.
-
mark_published
(user, audit=True, commit=True)[source]¶ Publish the content.
- Parameters
user (AUTH_USER_MODEL) – The user publishing the content.
audit (bool) – Call the
audit()
method if this is also an audit model.commit (bool) – Indicates the record should be saved.
-
mark_unpublished
(user, audit=True, commit=True)[source]¶ Un-publish the content.
- Parameters
user (AUTH_USER_MODEL) – The user publishing the content.
audit (bool) – Call the
audit()
method if this is also an audit model.commit (bool) – Indicates the record should be saved.
-
property
published_by_name
¶ Get the full name or user name of the user that published the record.
- Return type
str
Random Models¶
Provides a random character field.
Component Reference: Random Models
Resolved Models¶
Provides support for a resolution workflow.
Component Reference: Resolved Models
admin¶
-
class
superdjango.db.resolved.admin.
BaseResolvedByModelAdmin
(model, admin_site)[source]¶ Bases:
django.contrib.admin.options.ModelAdmin
Base admin class for models implementing the
ResolvedByModel
.
filters¶
-
class
superdjango.db.resolved.filters.
ResolvedByListFilter
(request, params, model, model_admin)[source]¶ Bases:
superdjango.db.audit.filters.BaseAuditListFilter
Filter for
resolved_by
.
models¶
-
class
superdjango.db.resolved.models.
ResolvedByModel
(*args, **kwargs)[source]¶ Bases:
django.db.models.base.Model
Represents a record (content of some sort) that may be resolved or unresolved.
- Parameters
is_resolved (BooleanField) – Indicates the content is resolved.
resolved_by_id (ForeignKey) – The user resolving the content.
resolved_dt (DateTimeField) – Date and time the news item was resolved.
-
mark_resolved
(user, audit=True, commit=True)[source]¶ Resolve the content.
- Parameters
user (AUTH_USER_MODEL) – The user resolving the content.
audit (bool) – Call the
audit()
method if this is also an audit model.commit (bool) – Indicates the record should be saved.
-
mark_unresolved
(user, audit=True, commit=True)[source]¶ Un-publish the content.
- Parameters
user (AUTH_USER_MODEL) – The user resolving the content.
audit (bool) – Call the
audit()
method if this is also an audit model.commit (bool) – Indicates the record should be saved.
-
property
resolved_by_name
¶ Get the full name or user name of the user that resolved the record.
- Return type
str
Reviewed Models¶
Provides support for a review workflow.
Component Reference: Reviewed Models
admin¶
-
class
superdjango.db.reviewed.admin.
BaseReviewedByModelAdmin
(model, admin_site)[source]¶ Bases:
django.contrib.admin.options.ModelAdmin
Base admin class for models implementing the
ReviewedByModel
.
filters¶
-
class
superdjango.db.reviewed.filters.
ReviewedByListFilter
(request, params, model, model_admin)[source]¶ Bases:
superdjango.db.audit.filters.BaseAuditListFilter
Filter for
reviewed_by
.
models¶
-
class
superdjango.db.reviewed.models.
ReviewedByModel
(*args, **kwargs)[source]¶ Bases:
django.db.models.base.Model
Represents a record (content of some sort) that may be reviewed.
Fields
The following fields are provided:
is_reviewed
reviewed_dt
reviewed_by
- Parameters
is_reviewed (BooleanField) – Indicates the content is reviewed.
reviewed_by_id (ForeignKey) – The user reviewing the content.
reviewed_dt (DateTimeField) – Date and time the news item was reviewed.
-
mark_reviewed
(user, audit=True, commit=True)[source]¶ Review the content.
- Parameters
user (AUTH_USER_MODEL) – The user reviewing the content.
audit (bool) – Call the
audit()
method if this is also an audit model.commit (bool) – Indicates the record should be saved.
-
mark_unreviewed
(user, audit=True, commit=True)[source]¶ Un-review the content.
- Parameters
user (AUTH_USER_MODEL) – The user publishing the content.
audit (bool) – Call the
audit()
method if this is also an audit model.commit (bool) – Indicates the record should be saved.
-
property
reviewed_by_name
¶ Get the full name or user name of the user that reviewed the record.
- Return type
str
Revised Models¶
A simple package that allows saving revisions of a record.
Component Reference: Revised Models
managers¶
models¶
-
class
superdjango.db.revised.models.
RevisedModel
(*args, **kwargs)[source]¶ Bases:
django.db.models.base.Model
Supports records with revisions.
- Parameters
is_previous_revision (BooleanField) – Indicates this is a previous revision.
previous_revision_id (ForeignKey) – The last or previous version of the record.
revision_by_id (ForeignKey) – The user that created the revision.
revision_dt (DateTimeField) – Date and time the revision was created.
revision_number (IntegerField) – The revision number for the record.
-
save_revision
(user, commit=True)[source]¶ Save a revision of the model.
- Parameters
user (AUTH_USER_MODEL) – The user creating the revision.
commit (bool) – Whether to save immediately.
Tip
The original instance is also not saved when
commit
isFalse
.Warning
Related records are not changed or duplicated during the revision.
- Returns
The revised record (model instance).
Sorted Models¶
A model and utilities for implementing record sortation.
Component Reference: Sorted Models
models¶
-
class
superdjango.db.sorted.models.
SortedModel
(*args, **kwargs)[source]¶ Bases:
django.db.models.base.Model
Allow a model to be easily sortable.
Fields
sort_order
Implementation
from superdjango.db.sorted.models import SortedModel class Task(SortedModel): # ... class Meta: ordering = ["sort_order"]
- Parameters
sort_order (IntegerField) – How the record should be sorted.
utils¶
Sortation utilities are separated from the SortedModel
in order to keep the model clean and prevent possible
collisions or conflicts with method names.
They may still be used in a declarative manner, for example:
from superdjango.db.sorted import utils as sortation
from .models import Task
task = Task.objects.get(pk=1234)
if sortation.has_previous_record(task):
previous_task = sortation.get_previous_record(task)
if sortation.has_next_record(task):
next_task = sortation.get_next_record(task)
-
superdjango.db.sorted.utils.
get_next_record
(instance, **criteria)[source]¶ Get the next record, if one exists.
- Parameters
instance – The instance to be checked.
criteria (dict) – Additional criteria to be given. This is useful when the record is embedded in a hierarchy.
- Return type
models.Model
- Returns
Returns the next instance or
None
if a next instance could not be found.
-
superdjango.db.sorted.utils.
get_previous_record
(instance, **criteria)[source]¶ Get the previous record, if one exists.
- Parameters
instance – The instance to be checked.
criteria (dict) – Additional criteria to be given. This is useful when the record is embedded in a hierarchy.
- Return type
models.Model
- Returns
Returns the previous instance or
None
if a previous instance could not be found.
-
superdjango.db.sorted.utils.
has_next_record
(instance, **criteria)[source]¶ Indicates whether a record exists with a higher sort order.
- Parameters
instance – The instance to be checked.
criteria (dict) – Additional criteria to be given. This is useful when the record is embedded in a hierarchy.
- Return type
bool
-
superdjango.db.sorted.utils.
has_previous_record
(instance, **criteria)[source]¶ Indicates whether a record exists with a lower sort order.
- Parameters
instance – The instance to be checked.
criteria (dict) – Additional criteria to be given. This is useful when the record is embedded in a hierarchy.
- Return type
bool
Slug Fields¶
Provides support for a automatic slug field.
Component Reference: Slug Fields
fields¶
-
class
superdjango.db.slug.fields.
AutoSlugField
(*args, **kwargs)[source]¶ Bases:
django.db.models.fields.SlugField
Automatically generate a slug from another field.
- Parameters
from_field (str) – The field from which the slug will be populated. This field must exist within the same model.
slug_using (callable) – The function to use for creating the slug. Defaults to Django’s implementation of
slugify()
.
Example of use:
class Project(models.Model): title = models.CharField(max_length=128) slug = AutoSlugField(from_field="title", max_length=128)
-
class
superdjango.db.slug.fields.
UniqueAutoSlugField
(*args, **kwargs)[source]¶ Bases:
superdjango.db.slug.fields.AutoSlugField
Like
superdjango.db.slug.fields.AutoSlugField
, but adds a unique constraint.Warning
Note that this causes additional database queries which may impact performance.
utils¶
-
superdjango.db.slug.utils.
unique_slugify
(record, value, callback=None, field='slug', queryset=None)[source]¶ Get a unique slug for a model instance.
- Parameters
record – The model instance.
value (str) – The value to be slugged.
callback (callable) – The function that converts the value to a slug.
field (str) – The name of the slug field.
queryset (django.db.models.QuerySet) – The queryset to use for finding duplicates. This will default to all records of the given record’s model.
- Return type
str
Timed Models¶
Create records that incorporate start/stop timing functionality.
Component Reference: Timed Models
models¶
-
class
superdjango.db.timed.models.
TimedModel
(*args, **kwargs)[source]¶ Bases:
django.db.models.base.Model
- Provides date/time fields for noting a starting time and ending time, as well as convenience methods for
calculating elapsed time.
from superdjango.db.timed.models import TimedModel class Meeting(TimedModel): end_date = models.DateField() end_time = models.TimeField() is_all_day = models.BooleanField() start_date = models.DateField() start_time = models.TimeField()
- Parameters
timer_elapsed_seconds (PositiveIntegerField) – Total seconds elapsed from start to end.
timer_is_running (BooleanField) – Indicates whether the timer is running.
timer_start_dt (DateTimeField) – Date and time the timer was started.
timer_stop_dt (DateTimeField) – Date and time the timer was stopped.
-
property
elapsed_duration
¶ Get the elapsed duration either as the current
timer_elapsed_seconds
or by callingget_elapsed_duration()
.- Return type
timedelta
-
get_elapsed_duration_display
()[source]¶ Get a human-friendly display for the duration.
- Return type
str
-
get_timer_elapsed_seconds
()[source]¶ Get the number of seconds that have passed since the timer started until now or until the item ended, if a stop datetime is available.
- Return type
int
This method will:
Calculate the elapsed seconds from the start datetime until the current datetime.
Also include the elapsed seconds already calculated.
-
reset_timer
(user, commit=True)[source]¶ Reset the current timer.
- Parameters
user (AUTH_USER_MODEL | None) – The user updating the record. If the record is an audit model, the
audit()
method will be called. PassNone
to suppress this behavior.commit (bool) – Indicates whether the record should be saved after resetting the timer.
- Return type
int
- Returns
The value of elapsed seconds prior to the reset.
This method will:
Remove the stop datetime and set elapsed seconds to
0
.Change the start datetime to the current datetime.
Ensure that the timer is still running.
-
start_timer
(user, commit=True)[source]¶ Start the timer.
- Parameters
user (AUTH_USER_MODEL | None) – The user updating the record. If the record is an audit model, the
audit()
method will be called. PassNone
to suppress this behavior.commit (bool) – Indicates whether the record should be saved after starting the timer.
- Return type
int
- Returns
The current elapsed seconds if the timer is already running. Otherwise,
0
.
This method will:
Set the start datetime to the current datetime.
Ensure that the time is running.
Leave the elapsed seconds unchanged.
-
stop_timer
(user, commit=True)[source]¶ Stop the timer.
- Parameters
user (AUTH_USER_MODEL | None) – The user updating the record. If the record is an audit model, the
audit()
method will be called. PassNone
to suppress this behavior.commit (bool) – Indicates whether the record should be saved after stopping the timer.
- Return type
int
- Returns
The elpased seconds.
This method will:
Set the stop datetime to the current datetime.
Update the elapsed seconds.
Ensure that the time is not running.
Trashed Models¶
Provides a workflow for trashed, but not deleted, models.
Component Reference: Trashed Models
managers¶
-
class
superdjango.db.trashed.managers.
TrashedManager
(*args, **kwargs)[source]¶ Bases:
django.db.models.manager.Manager
Work with records implementing
TrashModel
.Example:
class MyModel(TrashModel): objects = models.Manager() trashcan = TrashManager()
Note
If you want to always filter out trashed records, this manager must be the default.
Emptying the trash can.
-
empty
(confirmed=False, criteria=None)[source]¶ Empty the trash can by permanently removing all records marked as trash.
- Parameters
confirmed (bool) – Indicates the removal is confirmed. This is an extra precaution to prevent unintended deletion.
criteria (dict) – Additional criteria.
Example of using additional criteria:
# models.py from superdjango.db.audit.models import AddedByModel from superdjango.db.trash.managers import TrashManager from superdjango.db.trash.models import TrashModel class Task(AddedByModel, TrashModel): trashcan = TrashManager() # ... # views.py class EmptyTrash(FormView): def form_valid(self, form): criteria = { 'added_by': self.request.user, } Task.trashcan.empty(confirmed=True, criteria) # ...
-
models¶
-
class
superdjango.db.trashed.models.
TrashedModel
(*args, **kwargs)[source]¶ Bases:
django.db.models.base.Model
Allow a record to be marked as “trashed” without deleting it.
- Parameters
is_trashed (NullBooleanField) – Indicates this record is in the trash.
trashed_by_id (ForeignKey) – User that put the record in the trash.
trashed_dt (DateTimeField) – Date and time the record was trashed.