Media
This package contains all media-related models:
MediaFile
and
Directory
Directory
- class integreat_cms.cms.models.media.directory.Directory(*args, **kwargs)[source]
Bases:
AbstractBaseModel
Model representing a directory containing documents. This is only a virtual directory and does not necessarily exist on the actual file system. Each directory is tied to a region.
- Parameters:
id (BigAutoField) – Primary key: ID
name (CharField) – Name
created_date (DateTimeField) – Creation date. The date and time when the directory was created
is_hidden (BooleanField) – Hidden. Whether the directory is hidden in the regional media library
Relationship fields:
- Parameters:
region (
ForeignKey
toRegion
) – Region (related name:media_directories
)parent (
ForeignKey
toDirectory
) – Parent directory (related name:subdirectories
)
Reverse relationships:
- Parameters:
subdirectories (Reverse
ForeignKey
fromDirectory
) – All subdirectories of this media directory (related name ofparent
)files (Reverse
ForeignKey
fromMediaFile
) – All files of this media directory (related name ofparent_directory
)
- exception DoesNotExist[source]
Bases:
ObjectDoesNotExist
- exception MultipleObjectsReturned[source]
Bases:
MultipleObjectsReturned
- clean()[source]
Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.
- clean_fields(exclude=None)[source]
Clean all fields and raise a ValidationError containing a dict of all validation errors if any occur.
- created_date[source]
Type:
DateTimeField
Creation date. The date and time when the directory was created
- files[source]
Type: Reverse
ForeignKey
fromMediaFile
All files of this media directory (related name of
parent_directory
)
- full_clean(exclude=None, validate_unique=True, validate_constraints=True)[source]
Call clean_fields(), clean(), validate_unique(), and validate_constraints() on the model. Raise a ValidationError for any errors that occur.
- classmethod get_model_name_plural() str [source]
Get the plural representation of this model name
- Returns:
The plural model name
- Return type:
- get_next_by_created_date(*, field=<django.db.models.DateTimeField: created_date>, is_next=True, **kwargs)[source]
Finds next instance based on
created_date
. Seeget_next_by_FOO()
for more information.
- get_previous_by_created_date(*, field=<django.db.models.DateTimeField: created_date>, is_next=False, **kwargs)[source]
Finds previous instance based on
created_date
. Seeget_previous_by_FOO()
for more information.
- get_repr() str [source]
This overwrites the default Django
__repr__()
method which would return<Directory: Directory object (id)>
. It is used for logging.- Returns:
The canonical string representation of the directory
- Return type:
- id[source]
Type:
BigAutoField
Primary key: ID
Type:
BooleanField
Hidden. Whether the directory is hidden in the regional media library
- parent[source]
Type:
ForeignKey
toDirectory
Parent directory (related name:
subdirectories
)
- refresh_from_db(using=None, fields=None)[source]
Reload field values from the database.
By default, the reloading happens from the database this instance was loaded from, or by the read router if this instance wasn’t loaded from any database. The using parameter will override the default.
Fields can be used to specify which fields to reload. The fields should be an iterable of field attnames. If fields is None, then all non-deferred fields are reloaded.
When accessing deferred fields of an instance, the deferred loading of the field will call this method.
- region[source]
Type:
ForeignKey
toRegion
Region (related name:
media_directories
)
- save(force_insert=False, force_update=False, using=None, update_fields=None)[source]
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.
- save_base(raw=False, force_insert=False, force_update=False, using=None, update_fields=None)[source]
Handle the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending.
The ‘raw’ argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading.
- classmethod search(region: Region, query: str) QuerySet[Directory] [source]
Searches for all directories which match the given query in their name.
- serializable_value(field_name)[source]
Return the value of the field name for this instance. If the field is a foreign key, return the id value instead of the object. If there’s no Field object with this name on the model, return the model attribute’s value.
Used to serialize a field’s value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method.
- serialize() dict[str, Any] [source]
This method creates a serialized version of that object for later use in AJAX and JSON.
- subdirectories[source]
Type: Reverse
ForeignKey
fromDirectory
All subdirectories of this media directory (related name of
parent
)
Media File
This module contains the MediaFile
model as well as the helper functions
upload_path()
and upload_path_thumbnail()
which
are used to determine the file system path to which the files should be uploaded.
- class integreat_cms.cms.models.media.media_file.MediaFile(*args, **kwargs)[source]
Bases:
AbstractBaseModel
The MediaFile model is used to store basic information about files which are uploaded to the CMS. This is only a virtual document and does not necessarily exist on the actual file system. Each document is tied to a region via its directory.
- Parameters:
id (BigAutoField) – Primary key: ID
file (FileField) – File
thumbnail (FileField) – Thumbnail file
file_size (IntegerField) – File size
type (CharField) – File type
name (CharField) – Name
alt_text (CharField) – Description
uploaded_date (DateTimeField) – Uploaded date. The date and time when the media file was uploaded
last_modified (DateTimeField) – Last modified. The date and time when the physical media file was last modified
is_hidden (BooleanField) – Hidden. Whether the media file is hidden in the regional media library
Relationship fields:
- Parameters:
parent_directory (
ForeignKey
toDirectory
) – Parent directory (related name:files
)region (
ForeignKey
toRegion
) – Region (related name:files
)
Reverse relationships:
- Parameters:
icon_regions (Reverse
ForeignKey
fromRegion
) – All icon regions of this media file (related name oficon
)icon_organizations (Reverse
ForeignKey
fromOrganization
) – All icon organizations of this media file (related name oficon
)pois (Reverse
ForeignKey
fromPOI
) – All pois of this media file (related name oficon
)events (Reverse
ForeignKey
fromEvent
) – All events of this media file (related name oficon
)pages (Reverse
ForeignKey
fromPage
) – All pages of this media file (related name oficon
)
- exception DoesNotExist[source]
Bases:
ObjectDoesNotExist
- exception MultipleObjectsReturned[source]
Bases:
MultipleObjectsReturned
- clean()[source]
Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.
- clean_fields(exclude=None)[source]
Clean all fields and raise a ValidationError containing a dict of all validation errors if any occur.
- content_usages[source]
Check where this media file is embedded in the content
- Returns:
list with the search result
- events[source]
Type: Reverse
ForeignKey
fromEvent
All events of this media file (related name of
icon
)
- file_size[source]
Type:
IntegerField
File size
- full_clean(exclude=None, validate_unique=True, validate_constraints=True)[source]
Call clean_fields(), clean(), validate_unique(), and validate_constraints() on the model. Raise a ValidationError for any errors that occur.
- classmethod get_model_name_plural() str [source]
Get the plural representation of this model name
- Returns:
The plural model name
- Return type:
- get_next_by_last_modified(*, field=<django.db.models.DateTimeField: last_modified>, is_next=True, **kwargs)[source]
Finds next instance based on
last_modified
. Seeget_next_by_FOO()
for more information.
- get_next_by_uploaded_date(*, field=<django.db.models.DateTimeField: uploaded_date>, is_next=True, **kwargs)[source]
Finds next instance based on
uploaded_date
. Seeget_next_by_FOO()
for more information.
- get_previous_by_last_modified(*, field=<django.db.models.DateTimeField: last_modified>, is_next=False, **kwargs)[source]
Finds previous instance based on
last_modified
. Seeget_previous_by_FOO()
for more information.
- get_previous_by_uploaded_date(*, field=<django.db.models.DateTimeField: uploaded_date>, is_next=False, **kwargs)[source]
Finds previous instance based on
uploaded_date
. Seeget_previous_by_FOO()
for more information.
- get_repr() str [source]
This overwrites the default Django
__repr__()
method which would return<MediaFile: MediaFile object (id)>
. It is used for logging.- Returns:
The canonical string representation of the document
- Return type:
- get_type_display(*, field=<django.db.models.CharField: type>)[source]
Shows the label of the
type
. Seeget_FOO_display()
for more information.
- icon_organizations[source]
Type: Reverse
ForeignKey
fromOrganization
All icon organizations of this media file (related name of
icon
)
- icon_regions[source]
Type: Reverse
ForeignKey
fromRegion
All icon regions of this media file (related name of
icon
)
- icon_usages[source]
Check where a media file is used as icon
- Returns:
List of all objects that use this file as icon
- id[source]
Type:
BigAutoField
Primary key: ID
- is_embedded[source]
Check if a media file is embedded in the content
- Returns:
Whether a file is embedded
Type:
BooleanField
Hidden. Whether the media file is hidden in the regional media library
- is_only_used_in_past_events[source]
Check if a media file is used in past events only
- Returns:
if a media file is only used in past events
- last_modified[source]
Type:
DateTimeField
Last modified. The date and time when the physical media file was last modified
- objects = <django.db.models.manager.ManagerFromMediaFileQuerySet object>[source]
Django manager to access the ORM Use
MediaFile.objects.all()
to fetch all objects.Custom model manager for media file objects
- pages[source]
Type: Reverse
ForeignKey
fromPage
All pages of this media file (related name of
icon
)
- parent_directory[source]
Type:
ForeignKey
toDirectory
Parent directory (related name:
files
)
- parent_directory_id[source]
Internal field, use
parent_directory
instead.
- past_event_usages[source]
Count in how many past events this file is used
- Returns:
count of usages in past events
- pois[source]
Type: Reverse
ForeignKey
fromPOI
All pois of this media file (related name of
icon
)
- refresh_from_db(using=None, fields=None)[source]
Reload field values from the database.
By default, the reloading happens from the database this instance was loaded from, or by the read router if this instance wasn’t loaded from any database. The using parameter will override the default.
Fields can be used to specify which fields to reload. The fields should be an iterable of field attnames. If fields is None, then all non-deferred fields are reloaded.
When accessing deferred fields of an instance, the deferred loading of the field will call this method.
- region[source]
Type:
ForeignKey
toRegion
Region (related name:
files
)
- save(force_insert=False, force_update=False, using=None, update_fields=None)[source]
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.
- save_base(raw=False, force_insert=False, force_update=False, using=None, update_fields=None)[source]
Handle the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending.
The ‘raw’ argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading.
- classmethod search(region: Region, query: str) QuerySet [source]
Searches for all media files which match the given query in their name.
- serializable_value(field_name)[source]
Return the value of the field name for this instance. If the field is a foreign key, return the id value instead of the object. If there’s no Field object with this name on the model, return the model attribute’s value.
Used to serialize a field’s value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method.
- serialize() dict[str, Any] [source]
This methods creates a serialized string of that document. This can later be used in the AJAX calls.
- serialize_usages() dict[str, Any] [source]
This methods creates a serialized dict of the file’s usages. This can later be used in the AJAX calls.
- property thumbnail_url: str | None[source]
Return the path of the image that should be used as the thumbnail.
- Returns:
The path of the file. If the file is an image and no thumbnail could be generated the file itself will be returned.
- type[source]
Type:
CharField
File type
Choices:
image/png
image/jpeg
application/pdf
image/svg+xml
image/gif
application/msword
application/vnd.openxmlformats-officedocument.wordprocessingml.document
application/vnd.ms-excel
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
application/vnd.ms-powerpoint
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
- uploaded_date[source]
Type:
DateTimeField
Uploaded date. The date and time when the media file was uploaded
- class integreat_cms.cms.models.media.media_file.MediaFileQuerySet(model=None, query=None, using=None, hints=None)[source]
Bases:
QuerySet
Custom queryset for media files
- async abulk_create(objs, batch_size=None, ignore_conflicts=False, update_conflicts=False, update_fields=None, unique_fields=None)[source]
- aggregate(*args, **kwargs)[source]
Return a dictionary containing the calculations (aggregation) over the current queryset.
If args is present the expression is passed as a kwarg using the Aggregate object’s default alias.
- async aiterator(chunk_size=2000)[source]
An asynchronous iterator over the results from applying this QuerySet to the database.
- alias(*args, **kwargs)[source]
Return a query set with added aliases for extra data or aggregations.
- all()[source]
Return a new QuerySet that is a copy of the current one. This allows a QuerySet to proxy for a model manager in some cases.
- annotate(*args, **kwargs)[source]
Return a query set in which the returned objects have been annotated with extra data or aggregations.
- bulk_create(objs, batch_size=None, ignore_conflicts=False, update_conflicts=False, update_fields=None, unique_fields=None)[source]
Insert each of the instances into the database. Do not call save() on each of the instances, do not send any pre/post_save signals, and do not set the primary key attribute if it is an autoincrement field (except if features.can_return_rows_from_bulk_insert=True). Multi-table models are not supported.
- bulk_update(objs, fields, batch_size=None)[source]
Update the given fields in each of the given objects in the database.
- complex_filter(filter_obj)[source]
Return a new QuerySet instance with filter_obj added to the filters.
filter_obj can be a Q object or a dictionary of keyword lookup arguments.
This exists to support framework features such as ‘limit_choices_to’, and usually it will be more natural to use other methods.
- count()[source]
Perform a SELECT COUNT() and return the number of records as an integer.
If the QuerySet is already fully cached, return the length of the cached results set to avoid multiple SELECT COUNT(*) calls.
- create(**kwargs)[source]
Create a new object with the given kwargs, saving it to the database and returning the created object.
- dates(field_name, kind, order='ASC')[source]
Return a list of date objects representing all available dates for the given field_name, scoped to ‘kind’.
- datetimes(field_name, kind, order='ASC', tzinfo=None, is_dst=<object object>)[source]
Return a list of datetime objects representing all available datetimes for the given field_name, scoped to ‘kind’.
- defer(*fields)[source]
Defer the loading of data for certain fields until they are accessed. Add the set of deferred fields to any existing set of deferred fields. The only exception to this is if None is passed in as the only parameter, in which case removal all deferrals.
- distinct(*field_names)[source]
Return a new QuerySet instance that will select only distinct results.
- exclude(*args, **kwargs)[source]
Return a new QuerySet instance with NOT (args) ANDed to the existing set.
- explain(*, format=None, **options)[source]
Runs an EXPLAIN on the SQL query this QuerySet would perform, and returns the results.
- extra(select=None, where=None, params=None, tables=None, order_by=None, select_params=None)[source]
Add extra SQL fragments to the query.
- filter(*args, **kwargs)[source]
Return a new QuerySet instance with the args ANDed to the existing set.
- filter_unused() MediaFileQuerySet [source]
Filter for unused media files
- Returns:
The queryset of unused media files
- Return type:
- get(*args, **kwargs)[source]
Perform the query and return a single object matching the given keyword arguments.
- get_or_create(defaults=None, **kwargs)[source]
Look up an object with the given kwargs, creating one if necessary. Return a tuple of (object, created), where created is a boolean specifying whether an object was created.
- in_bulk(id_list=None, *, field_name='pk')[source]
Return a dictionary mapping each of the given IDs to the object with that ID. If id_list isn’t provided, evaluate the entire QuerySet.
- iterator(chunk_size=None)[source]
An iterator over the results from applying this QuerySet to the database. chunk_size must be provided for QuerySets that prefetch related objects. Otherwise, a default chunk_size of 2000 is supplied.
- latest(*fields)[source]
Return the latest object according to fields (if given) or by the model’s Meta.get_latest_by.
- only(*fields)[source]
Essentially, the opposite of defer(). Only the fields passed into this method and that are not already specified as deferred are loaded immediately when the queryset is evaluated.
- property ordered[source]
Return True if the QuerySet is ordered – i.e. has an order_by() clause or a default ordering on the model (or is empty).
Return a new QuerySet instance that will prefetch the specified Many-To-One and Many-To-Many related objects when the QuerySet is evaluated.
When prefetch_related() is called more than once, append to the list of prefetch lookups. If prefetch_related(None) is called, clear the list.
- select_for_update(nowait=False, skip_locked=False, of=(), no_key=False)[source]
Return a new QuerySet instance that will select objects with a FOR UPDATE lock.
Return a new QuerySet instance that will select related objects.
If fields are specified, they must be ForeignKey fields and only those related objects are included in the selection.
If select_related(None) is called, clear the list.
- update(**kwargs)[source]
Update all elements in the current QuerySet, setting all the given fields to the appropriate values.
- integreat_cms.cms.models.media.media_file.file_size_limit(value: FieldFile) None [source]
This function checks if the uploaded file exceeds the file size limit
- Parameters:
value (FieldFile) – the size of upload file
- Raises:
ValidationError – when the file size exceeds the size given in the settings.
- Return type:
None
- integreat_cms.cms.models.media.media_file.upload_path(instance: MediaFile, filename: str) str [source]
This function calculates the path for a file which is uploaded to the media library. It contains the region id, the current year and month as subdirectories and the filename. It also contains the current epoch time to make sure that no path will be used twice. It is just the provisionally requested path for the media storage. If it already exists, Django will automatically append a random string to make sure the file name is unique.
- integreat_cms.cms.models.media.media_file.upload_path_thumbnail(instance: MediaFile, filename: str) str [source]
This function derives the upload path of a thumbnail file from it’s original file. This makes it a bit easier to determine which thumbnail belongs to which file if there are multiple files with the same file name (in which case Django automatically appends a random string to the original’s file name).
E.g. if the files
A.jpg
andA_thumbnail.jpg
already exist, andA.jpg
is uploaded again, the resulting file names might be e.g.A_EOHRFQ2.jpg
andA_thumbnail_IWxPiOq.jpg
, while with this function, the thumbnail will be stored asA_EOHRFQ2_thumbnail.jpg
, making it easier to examine these files on the file system.