Django 3 Web Development Cookbook
上QQ阅读APP看书,第一时间看更新

How it works...

Django model forms are created dynamically from models. They provide the specified fields from the model so you don't need to redefine them manually in the form. In the preceding example, we created a model form for the Idea model. When we save the form, the form knows how to save each field in the database, as well as how to upload the files and save them in the media directory.

The upload_to() function in our example is used for saving the image to a specific directory and defining its name such that it wouldn't clash with filenames for other model instances. Each file will be saved under a path such as ideas/2020/01/0422c6fe-b725-4576-8703-e2a9d9270986.jpg, which consists of the year and month of the upload and the primary key of the Idea instance.

Some filesystems (such as FAT32 and NTFS) have a limited amount of files available per directory; therefore, it is a good practice to divide them into directories by upload date, alphabet, or other criteria.

We are creating three image versions using ImageSpecField from django-imagekit:

  • picture_social is used for social sharing.
  • picture_large is used for the detail view.
  • picture_thumbnail is used for the list view.

Image versions are not linked in the database but just saved in the default file storage under a file path such as CACHE/images/ideas/2020/01/0422c6fe-b725-4576-8703-e2a9d9270986/.

In the template, you can use the original or a specific image version, as follows:

<img src="{{ idea.picture.url }}" alt="" />
<
img src="{{ idea.picture_large.url }}" alt="" />

At the end of the Idea model definition, we overwrite the delete() method to delete the image versions and the picture from the disk just before deleting the instance of Idea itself.