ObjectDownloadView¶
ObjectDownloadView
serves files managed in models with file fields
such as FileField
or
ImageField
.
Use this view like Django’s builtin
DetailView
.
Additional options allow you to store file metadata (size, content-type, …) in the model, as deserialized fields.
Simple example¶
Given a model with a FileField
:
from django.db import models
class Document(models.Model):
slug = models.SlugField()
file = models.FileField(upload_to="object")
Setup a view to stream the file
attribute:
from django_downloadview import ObjectDownloadView
from demoproject.object.models import Document
#: Serve ``file`` attribute of ``Document`` model.
default_file_view = ObjectDownloadView.as_view(model=Document)
ObjectDownloadView
inherits from
BaseDetailView
, i.e. it expects either
slug
or pk
:
from django.urls import re_path
from demoproject.object import views
app_name = "object"
urlpatterns = [
re_path(
r"^default-file/(?P<slug>[a-zA-Z0-9_-]+)/$",
views.default_file_view,
name="default_file",
),
]
Base options¶
ObjectDownloadView
inherits from
DownloadMixin
, which has various
options such as basename
or attachment
.
Serving specific file field¶
If your model holds several file fields, or if the file field name is not
“file”, you can use ObjectDownloadView.file_field
to specify the field
to use.
Here is a model where there are two file fields:
from django.db import models
class Document(models.Model):
slug = models.SlugField()
file = models.FileField(upload_to="object")
another_file = models.FileField(upload_to="object-other")
Then here is the code to serve “another_file” instead of the default “file”:
from django_downloadview import ObjectDownloadView
from demoproject.object.models import Document
#: Serve ``another_file`` attribute of ``Document`` model.
another_file_view = ObjectDownloadView.as_view(
model=Document, file_field="another_file"
)
Mapping file attributes to model’s¶
Sometimes, you use Django model to store file’s metadata. Some of this metadata can be used when you serve the file.
As an example, let’s consider the client-side basename lives in model and not in storage:
from django.db import models
class Document(models.Model):
slug = models.SlugField()
file = models.FileField(upload_to="object")
basename = models.CharField(max_length=100)
Then you can configure the ObjectDownloadView.basename_field
option:
from django_downloadview import ObjectDownloadView
from demoproject.object.models import Document
#: Serve ``file`` attribute of ``Document`` model, using client-side filename
#: from model.
deserialized_basename_view = ObjectDownloadView.as_view(
model=Document, basename_field="basename"
)
Note
basename
could have been a model’s property instead of a CharField
.
See details below for a full list of options.