upload.models - Models for upload app
- class upload.models.UploadSession(*args, **kwargs)
Bases:
ModelRepresents a file upload session. This model is used to track the files that a user uploads during a session.
The following state diagram illustrates the possible states and transitions for an UploadSession:
flowchart TD CREATED --> EXPIRED CREATED --> UPLOADING UPLOADING --> CREATED UPLOADING --> EXPIRED UPLOADING --> COPYING_IN_PROGRESS UPLOADING --> REMOVING_IN_PROGRESS COPYING_IN_PROGRESS --> COPYING_FAILED COPYING_IN_PROGRESS --> STORED STORED --> COPYING_IN_PROGRESS STORED --> REMOVING_IN_PROGRESS REMOVING_IN_PROGRESS --> CREATEDUploadSession State Diagram
- exception SessionLimitExceeded
Bases:
ExceptionRaised when creating a new session would exceed a user’s open-session limit.
- class SessionStatus(*values)
Bases:
TextChoicesThe status of the session.
- CREATED = 'CR'
- EXPIRED = 'EX'
- UPLOADING = 'UG'
- COPYING_IN_PROGRESS = 'CP'
- STORED = 'SD'
- COPYING_FAILED = 'FD'
- REMOVING_IN_PROGRESS = 'RP'
- token
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- started_at
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- status
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- user
Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.
In the example:
class Child(Model): parent = ForeignKey(Parent, related_name='children')
Child.parentis aForwardManyToOneDescriptorinstance.
- last_upload_interaction_time
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- objects = <upload.managers.UploadSessionManager object>
- classmethod new_session(user: User | None = None, enforce_limit: bool = False) UploadSession
Start a new upload session.
- Parameters:
user – The user that will own the session.
enforce_limit – If True (and a user is given), atomically check that creating this session will not push the user over the UPLOAD_SESSION_MAX_CONCURRENT_OPEN limit. The check and the insert are performed inside a transaction with the user row locked (
SELECT ... FOR UPDATE), serializing concurrent attempts for the same user and closing the time-of-check-to-time-of-use race window.
- Raises:
UploadSession.SessionLimitExceeded – If
enforce_limitis True and creating this session would exceed the user’s open session limit.
- property upload_size: int
Get total size (in bytes) of all uploaded files in this session. This includes the size of both temporary and permanent files.
- property file_count: int
Get the total count of temporary + permanent uploaded files.
- property expires_at: datetime | None
Calculate this session’s expiration time. Only sessions in the CREATED, UPLOADING, or EXPIRED state can have an expiration time. Returns None for sessions in other states, or if the upload session expiry feature is disabled.
- property is_expired: bool
Determine if this session has expired. A session is considered expired if it is in the EXPIRED state, or if it has gone past its expiration time.
- property expires_soon: bool
Determine if this session will expire within the set expiration reminder time.
- expires_within(minutes: int) bool
Determine if this session will expire within the given number of minutes.
- Parameters:
minutes – The number of minutes in the future to check for expiration.
- Returns:
True if the session will expire before the given number of minutes from now, False otherwise.
- expire() None
Set the status of this session to EXPIRED, but only if the current status is CREATED or UPLOADING.
- Raises:
ValueError – If the current status is not CREATED or UPLOADING.
- touch(save: bool = True) None
Reset the last upload interaction time to the current time.
- add_temp_file(file: UploadedFile) TempUploadedFile
Add a temporary uploaded file to this session.
- remove_temp_file_by_name(name: str) None
Remove a temporary uploaded file from this session by name.
- get_file_by_name(name: str) BaseUploadedFile
Get an uploaded file in this session by name. The file can be either temporary or permanent.
- Parameters:
name – The name of the file to find
- get_temporary_uploads() list[TempUploadedFile]
Get a list of temporary uploaded files associated with this session.
May be empty if temp uploads have already been moved to permanent storage.
- get_permanent_uploads() list[PermUploadedFile]
Get a list of permanent uploaded files associated with this session.
May be empty if temp uploads have not been moved.
- get_uploads() list[TempUploadedFile] | list[PermUploadedFile]
Get a list of temporary or permanent uploaded files associated with this session. Will return temporary files if in the UPLOADING state, and permanent files if in the STORED state.
- remove_temp_uploads(save: bool = True) None
Remove all temp uploaded files associated with this session.
- make_uploads_permanent() None
Make all temporary uploaded files associated with this session permanent.
- copy_session_uploads(destination: str) tuple[list[str], list[str]]
Copy permanent uploaded files associated with this session to a destination directory.
- Parameters:
destination – The destination directory
- Returns:
A tuple containing lists of copied and missing files
- get_quantity_and_unit_of_measure() str
Create a human-readable statement of how many files are in this session.
If the session is in the state UPLOADING, returns a count of temp files. If the session is in the state STORED, returns a count of permanent files. If the session is in the state CREATED, returns an appropriate value that indicates the lack of files.
Uses the ACCEPTED_FILE_FORMATS setting to group file types together.
- Returns:
A human readable count and size of all files in this session.
- exception DoesNotExist
Bases:
ObjectDoesNotExist
- exception MultipleObjectsReturned
Bases:
MultipleObjectsReturned
- exception NotUpdated
Bases:
ObjectNotUpdated,DatabaseError
- get_next_by_last_upload_interaction_time(*, field=<django.db.models.fields.DateTimeField: last_upload_interaction_time>, is_next=True, **kwargs)
- get_next_by_started_at(*, field=<django.db.models.fields.DateTimeField: started_at>, is_next=True, **kwargs)
- get_previous_by_last_upload_interaction_time(*, field=<django.db.models.fields.DateTimeField: last_upload_interaction_time>, is_next=False, **kwargs)
- get_previous_by_started_at(*, field=<django.db.models.fields.DateTimeField: started_at>, is_next=False, **kwargs)
- get_status_display(*, field=<django.db.models.fields.CharField: status>)
- id
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- in_progress_submission
Accessor to the related object on the reverse side of a one-to-one relation.
In the example:
class Restaurant(Model): place = OneToOneField(Place, related_name='restaurant')
Place.restaurantis aReverseOneToOneDescriptorinstance.
- permuploadedfile_set
Accessor to the related objects manager on the reverse side of a many-to-one relation.
In the example:
class Child(Model): parent = ForeignKey(Parent, related_name='children')
Parent.childrenis aReverseManyToOneDescriptorinstance.Most of the implementation is delegated to a dynamically defined manager class built by
create_reverse_many_to_one_manager()defined below.
- submission_set
Accessor to the related objects manager on the reverse side of a many-to-one relation.
In the example:
class Child(Model): parent = ForeignKey(Parent, related_name='children')
Parent.childrenis aReverseManyToOneDescriptorinstance.Most of the implementation is delegated to a dynamically defined manager class built by
create_reverse_many_to_one_manager()defined below.
- tempuploadedfile_set
Accessor to the related objects manager on the reverse side of a many-to-one relation.
In the example:
class Child(Model): parent = ForeignKey(Parent, related_name='children')
Parent.childrenis aReverseManyToOneDescriptorinstance.Most of the implementation is delegated to a dynamically defined manager class built by
create_reverse_many_to_one_manager()defined below.
- user_id
- upload.models.session_upload_location(instance: TempUploadedFile, filename: str) str
Generate the upload location for a session file.
- class upload.models.BaseUploadedFile(*args, **kwargs)
Bases:
ModelBase class for uploaded files with shared methods.
- uuid
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- name
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- session
Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.
In the example:
class Child(Model): parent = ForeignKey(Parent, related_name='children')
Child.parentis aForwardManyToOneDescriptorinstance.
- file_upload
The descriptor for the file attribute on the model instance. Return a FieldFile when accessed so you can write code like:
>>> from myapp.models import MyModel >>> instance = MyModel.objects.get(pk=1) >>> instance.file.size
Assign a file object on assignment so you can do:
>>> with open('/path/to/hello.world') as f: ... instance.file = File(f)
- property exists: bool
Determine if the file this object represents exists on the file system.
- Returns:
True if file exists, False otherwise
- Return type:
(bool)
- copy(new_path: str) None
Copy this file to a new path.
- Parameters:
new_path – The new path to copy this file to
- remove() None
Remove this file from the file system.
- get_file_media_url() str
Generate the media URL to this file.
- Raises:
FileNotFoundError if the file does not exist. –
- get_file_access_url() str
Generate URL to request access for this file.
The URL is keyed by the file’s opaque
uuidso the underlying upload session token never appears in URLs exposed to the client.
- session_id
- class upload.models.TempUploadedFile(*args, **kwargs)
Bases:
BaseUploadedFileRepresent a temporary file that a user uploaded during an upload session.
- file_upload
The descriptor for the file attribute on the model instance. Return a FieldFile when accessed so you can write code like:
>>> from myapp.models import MyModel >>> instance = MyModel.objects.get(pk=1) >>> instance.file.size
Assign a file object on assignment so you can do:
>>> with open('/path/to/hello.world') as f: ... instance.file = File(f)
- move_to_permanent_storage() None
Move the file from TempFileStorage to UploadedFileStorage.
- exception DoesNotExist
Bases:
ObjectDoesNotExist
- exception MultipleObjectsReturned
Bases:
MultipleObjectsReturned
- exception NotUpdated
Bases:
ObjectNotUpdated,DatabaseError
- id
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- name
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- objects = <django.db.models.manager.Manager object>
- session
Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.
In the example:
class Child(Model): parent = ForeignKey(Parent, related_name='children')
Child.parentis aForwardManyToOneDescriptorinstance.
- session_id
- uuid
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- class upload.models.PermUploadedFile(*args, **kwargs)
Bases:
BaseUploadedFileRepresent a file that a user uploaded and has been stored.
- file_upload
The descriptor for the file attribute on the model instance. Return a FieldFile when accessed so you can write code like:
>>> from myapp.models import MyModel >>> instance = MyModel.objects.get(pk=1) >>> instance.file.size
Assign a file object on assignment so you can do:
>>> with open('/path/to/hello.world') as f: ... instance.file = File(f)
- exception DoesNotExist
Bases:
ObjectDoesNotExist
- exception MultipleObjectsReturned
Bases:
MultipleObjectsReturned
- exception NotUpdated
Bases:
ObjectNotUpdated,DatabaseError
- id
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- name
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- objects = <django.db.models.manager.Manager object>
- session
Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.
In the example:
class Child(Model): parent = ForeignKey(Parent, related_name='children')
Child.parentis aForwardManyToOneDescriptorinstance.
- session_id
- uuid
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- upload.models.delete_file_on_model_delete(sender: TempUploadedFile | PermUploadedFile, instance: TempUploadedFile | PermUploadedFile, **kwargs) None
Delete the actual file when an uploaded file model instance is deleted.
- Parameters:
sender – The model class that sent the signal
instance – The model uploaded file instance being deleted
**kwargs – Additional keyword arguments passed to the signal handler