ImageField – Django Models
ImageField is a FileField with uploads restricted to image formats only. Before uploading files, one needs to specify a lot of settings so that file is securely saved and can be retrieved in a convenient manner. The default form widget for this field is a ClearableFileInput. In addition to the special attributes that are available for FileField, an ImageField also has height and width attributes.
ImageField requires the Pillow library. To install the same run,
pip install Pillow
Syntax
field_name = models.ImageField(upload_to=None, height_field=None, width_field=None, max_length=100, **options)
ImageField has following optional arguments:
ImageField.upload_to
This attribute provides a way of setting the upload directory and file name, and can be set in two ways. In both cases, the value is passed to the Storage.save() method. If you specify a string value, it may contain strftime() formatting, which will be replaced by the date/time of the file upload (so that uploaded files don’t fill up the given directory). For example:
class MyModel(models.Model): # file will be uploaded to MEDIA_ROOT / uploads upload = models.ImageField(upload_to = 'uploads/' ) # or... # file will be saved to MEDIA_ROOT / uploads / 2015 / 01 / 30 upload = models.ImageField(upload_to = 'uploads/% Y/% m/% d/' ) |
If you are using the default FileSystemStorage, the string value will be appended to your MEDIA_ROOT
path to form the location on the local filesystem where uploaded files will be stored. If you are using different storage, check that storage’s documentation to see how it handles upload_to
.
upload_to
may also be a callable, such as a function. This will be called to obtain the upload path, including the filename. This callable must accept two arguments and return a Unix-style path (with forward slashes) to be passed along to the storage system. The two arguments are:
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) |
ImageField.height_field
Name of a model field which will be auto-populated with the height of the image each time the model instance is saved.
ImageField.width_field
Name of a model field which will be auto-populated with the width of the image each time the model instance is saved.
Django Model ImageField Explanation
Illustration of ImageField using an Example. Consider a project named geeksforgeeks
having an app named geeks
.
Enter the following code into models.py
file of geeks app.
from django.db import models from django.db.models import Model # Create your models here. class GeeksModel(Model): geeks_field = models.ImageField() |
Add the geeks app to INSTALLED_APPS
# Application definition INSTALLED_APPS = [ 'django.contrib.admin' , 'django.contrib.auth' , 'django.contrib.contenttypes' , 'django.contrib.sessions' , 'django.contrib.messages' , 'django.contrib.staticfiles' , 'geeks' , ] |
Now when we run makemigrations
command from the terminal,
Python manage.py makemigrations
A new folder named migrations would be created in geeks
directory with a file named 0001_initial.py
# Generated by Django 2.2.5 on 2019-09-25 06:00 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name = 'GeeksModel' , fields = [ ( 'id' , models.AutoField( auto_created = True , primary_key = True , serialize = False , verbose_name = 'ID' )), ( 'geeks_field' , models.ImageField()), ], ), ] |
Now run,
Python manage.py migrate
Thus, an geeks_field
ImageField is created when you run migrations on the project. It is a field to store valid image files.
How to use ImageField ?
ImageField is used for storing valid image files into the database. One can any type of image file in ImageField. Let’s try storing an image in the model created above.
- To start creating instances of model, create an admin account by using the following command.
Python manage.py createsuperuser
- Enter a username, email and a secure password. Then in your browser enter the following URL.
http://localhost:8000/admin/
- 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
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. See the validators documentation for more information. |
Unique | If True, this field must be unique throughout the table. |
Last Updated on November 13, 2021 by admin