Open In App

ImageField – Django forms

Improve
Improve
Like Article
Like
Save
Share
Report

ImageField in Django Forms is a input field for upload of image files. The default widget for this input is ClearableFileInput. It normalizes to: An UploadedFile object that wraps the file content and file name into a single object. This article revolves about how to upload images with Django forms and how can you save that to the database.
Note: 
 

  • When Django handles a file upload, the file data ends up placed in request.FILES (for more on the request object see the documentation for request and response objects).
  • While working with files, make sure the HTML form tag contains enctype=”multipart/form-data” property.

Syntax
 

field_name = forms.ImageField(**options)

 

Django form ImageField Explanation

Illustration of ImageField using an Example. Consider a project named geeksforgeeks having an app named geeks. 
 

Refer to the following articles to check how to create a project and an app in Django. 
 

Enter the following code into forms.py file of geeks app. 
 

Python3




from django import forms
 
class GeeksForm(forms.Form):
    name = forms.CharField()
    geeks_field = forms.ImageField()


Add the geeks app to INSTALLED_APPS 
 

Python3




# Application definition
 
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'geeks',
]


Now to render this form into a view we need a view and a URL mapped to that URL. Let’s create a view first in views.py of geeks app, 
 

Python3




from django.shortcuts import render
from .forms import GeeksForm
 
# Create your views here.
def home_view(request):
    context = {}
    context['form'] = GeeksForm()
    return render( request, "home.html", context)


Here we are importing that particular form from forms.py and creating an object of it in the view so that it can be rendered in a template. 
Now, to initiate a Django form you need to create home.html where one would be designing the stuff as they like. Let’s create a form in home.html.
 

html




<form method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Submit">
</form>


Finally, a URL to map to this view in urls.py 
 

Python3




from django.urls import path
 
# importing views from views..py
from .views import home_view
 
urlpatterns = [
    path('', home_view ),
]


Let’s run the server and check what has actually happened, Run 
 

Python manage.py runserver

 

django-forms-imagefield

Thus, an geeks_field ImageField is created by replacing “_” with ” “. It is a field to input image files from the user.
 

How to upload Files using ImageField – Django Forms ?

ImageField is used for input of image files in the database. One can input Email Id, etc. Till now we have discussed how to implement ImageField but how to use it in the view for performing the logical part. To perform some logic we would need to get the value entered into field into a python string instance. 
ImageField is different from other fields and it needs to be handled properly. As stated above, data fetched from a ImageField would be stored in request.FILES object. Let’s create a ImageField in Django models to demonstrate the saving of images using forms in database. To get working code for upload of files from github click here
In models.py, 
 

Python3




from django.db import models
 
# Create your models here.
class GeeksModel(models.Model):
    title = models.CharField(max_length = 200)
    img = models.ImageField(upload_to = "images/")
 
    def __str__(self):
        return self.title


In views.py,
 

Python3




from django.shortcuts import render
from .forms import GeeksForm
from .models import GeeksModel
 
# Create your views here.
def home_view(request):
    context = {}
    if request.method == "POST":
        form = GeeksForm(request.POST, request.FILES)
        if form.is_valid():
            name = form.cleaned_data.get("name")
            img = form.cleaned_data.get("geeks_field")
            obj = GeeksModel.objects.create(
                                 title = name,
                                 img = img
                                 )
            obj.save()
            print(obj)
    else:
        form = GeeksForm()
    context['form']= form
    return render(request, "home.html", context)


Let’s explain what this code does, this code saves the file uploaded by the user in GeeksModel ImageField Database. Whenever a file is uploaded, it is saved to request.FILES object with key as name of the field. So we have created a model where image uploaded by the user is saved. Let’s try saving a image file to the database now.
 

django-forms-imagefield-2

It has loaded successfully and file is saved in GeeksModel of geeks app. Above object is printed and hence instance of obj has been created. 
 

django-forms-imagefield-3

 

Core Field Arguments

Core Field arguments 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 required = False to ImageField will enable it to be left blank by the user. Each Field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted:
 

.math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; }

 

Field Options Description
required By default, each Field class assumes the value is required, so to make it not required you need to set required=False
label The label argument lets you specify the “human-friendly” label for this field. This is used when the Field is displayed in a Form.
label_suffix The label_suffix argument lets you override the form’s label_suffix on a per-field basis.
widget The widget argument lets you specify a Widget class to use when rendering this Field. See Widgets for more information.
help_text The help_text argument lets you specify descriptive text for this Field. If you provide help_text, it will be displayed next to the Field when the Field is rendered by one of the convenience Form methods. 
 
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.
validators The validators argument lets you provide a list of validation functions for this field. 
 
localize The localize argument enables the localization of form data input, as well as the rendered output.
disabled. The disabled boolean argument, when set to True, disables a form field using the disabled HTML attribute so that it won’t be editable by users. 
 

 



Last Updated : 30 Jun, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads