Ad Code



How to add image field in python django model

Django models are a built-in feature that Django uses to create tables, their fields, and various constraints.

Python django model

In short, Django models are the SQL of the database used with Django. SQL (Structured Query Language) is complex and it involves creating, deleting, updating, or any other query related to the database. Django models simplify tasks and manage tables as models. Typically, each model maps to a single database table.

When creating a Django model then assign every field of the database with its behavior related to the operation of the table with its accessing entities.

Then if you want to add an image field in the model and assign it to add image behavior with Django admin and forms then required to install the bellow package:-

pip install Pillow

This package is a python imaging library that contains image processing capability with a python interpreter.

The core image library is designed for fast access to data stored in a few basic pixel formats. It should provide a solid foundation for a general image processing tool.

After installing this package you can add an image field in the Django model like this-

from django.db import models

class Product(models.Model):
  image = models.ImageField(upload_to=None, height_field=None, width_field=None, max_length=100, **options)

The ImageField require to set MEDIA_ROOT for upload path in project

MEDIA_ROOT = BASE_DIR / 'uploads/'

also, you can set upload_to='[path of the upload dir]', this path has inside MEDIA_ROOT directory and upload images.

also, you can set height, width and max length, and many more options to follow the documentation.

If you are registered this model for admin then this automatically creates an image upload field in add and edit form of the admin section, and the file upload and save in given directory, and the name of the file is in the database without writing any backend login, its manage by the pillow package.

Python django model image upload field

Post a Comment


Ad Code