Storing Files on Model Instances
So far, we have manually managed the uploading and saving of files. You can also associate a file with a model instance by assigning the path to which it was saved to a CharField
. However, as with much of Django, this capability (and more) is already provided with the models.FileField
class. FileField
instances do not actually store the file data; instead, they store the path where the file is stored (like a CharField
would), but they also provide helper methods. These methods assist with loading files (so you do not have to manually open them) and generating disk paths for you based on the ID of the instance (or other attributes).
FileField
can accept two specific optional arguments in its constructor (as well as the base Field
arguments, such as required
, unique
, help_text
, and so on):
max_length
: Likemax_length
in the form'sImageField
, this is the maximum length of the filename that is allowed.upload_to
: Theupload_to
argument...