ImageField - Django Models
ImageField is a specialized version of Django's FileField designed to handle image uploads. It restricts uploads to image formats and provides additional attributes for storing image dimensions.
- Default form widget: ClearableFileInput
- Requires: Pillow library for image processing
Install Pillow with:
pip install Pillow
Syntax
field_name = models.ImageField(
upload_to=None,
height_field=None,
width_field=None,
max_length=100,
**options
)
Key Arguments for ImageField
Argument | Description |
---|---|
instance | An instance of the model where the ImageField is defined. More specifically, this is a particular instance where the current file is being attached. |
filename | The filename that was originally given to the file. This may or may not be taken into account when determining the final destination path |
For example:
def user_directory_path(instance, filename):
# file will be uploaded to MEDIA_ROOT / user_<id>/<filename>
return 'user_{0}/{1}'.format(instance.user.id, filename)
class MyModel(models.Model):
upload = models.ImageField(upload_to = user_directory_path)
height_field and width_field
Names of model fields (usually IntegerFields) that will be automatically populated with the height and width of the uploaded image whenever the model instance is saved.
Example: Using ImageField in a Model
Assuming a Django project geeksforgeeks with an app geeks:
Refer to the following articles to check how to create a project and an app in Django.
Enter the following code into models.py file of geeks app.
from django.db import models
from django.db.models import Model
class GeeksModel(Model):
geeks_field = models.ImageField()
Setup and Migration
1. Add your app to INSTALLED_APPS in settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'geeks',
]
2. Run migrations:
Python manage.py makemigrations
python manage.py migrate
Using ImageField with Django Admin
1. Create a superuser to access the admin interface:
python manage.py createsuperuser
2. Run the development server and log in to the admin:
http://localhost:8000/admin/
3. Add new instances of your model and upload images via the admin panel.
Go to add in front of Geeks Models.
Choose the file you want to upload and click on save. Now let's check it in admin server. We have created an instance of GeeksModel.
Field Options for ImageField
Field Options are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument null = True
to ImageField will enable it to store empty values for that table in relational database. Here are the field options and attributes that an ImageField can use.
Field Options | Description |
---|---|
Null | If True, Django will store empty values as NULL in the database. Default is False. |
Blank | If True, the field is allowed to be blank. Default is False. |
db_column | The name of the database column to use for this field. If this isn’t given, Django will use the field’s name. |
Default | The default value for the field. This can be a value or a callable object. If callable it will be called every time a new object is created. |
help_text | Extra “help” text to be displayed with the form widget. It’s useful for documentation even if your field isn’t used on a form. |
primary_key | If True, this field is the primary key for the model. |
editable | If False, the field will not be displayed in the admin or any other ModelForm. They are also skipped during model validation. Default is True. |
error_messages | The error_messages argument lets you override the default messages that the field will raise. Pass in a dictionary with keys matching the error messages you want to override. |
help_text | Extra “help” text to be displayed with the form widget. It’s useful for documentation even if your field isn’t used on a form. |
verbose_name | A human-readable name for the field. If the verbose name isn’t given, Django will automatically create it using the field’s attribute name, converting underscores to spaces. |
validators | A list of validators to run for this field. |
Unique | If True, this field must be unique throughout the table. |