The Wayback Machine - https://web.archive.org/web/20241126212324/https://www.geeksforgeeks.org/django-forms/
Open In App

Django Forms

Last Updated : 21 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

When one creates a Form class, the most important part is defining the fields of the form. Each field has custom validation logic, along with a few other hooks. This article revolves around various fields one can use in a form along with various features and techniques concerned with Django Forms.

Django Forms

Forms are used for taking input from the user in some manner and using that information for logical operations on databases. For example, Registering a user by taking input such as his name, email, password, etc.

Django maps the fields defined in Django forms into HTML input fields. Django handles three distinct parts of the work involved in forms:

  • Preparing and restructuring data to make it ready for rendering.
  • Creating HTML forms for the data.
  • Receiving and processing submitted forms and data from the client.
Django Forms

Note that all types of work done by forms in Django can be done with advanced HTML stuff, but Django makes it easier and efficient especially the validation part. Once you get hold of forms in Django you will just forget about HTML forms.

Syntax :  Django Fields work like Django Model Fields and have the syntax:

 field_name = forms.FieldType(**options) 

Example

Python
from django import forms

# creating a form
class GeeksForm(forms.Form):
    title = forms.CharField()
    description = forms.CharField() 

To use Forms in Django, one needs to have a project and an app working in it. After you start an app you can create a form in app/forms.py. Before starting to use a form let’s check how to start a project and implement Django Forms.

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

Creating Forms in Django

Creating a form in Django is completely similar to creating a model, one needs to specify what fields would exist in the form and of what type. For example, to input, a registration form one might need First Name (CharField), Roll Number (IntegerField), and so on. 

Syntax: 

from django import forms

class FormName(forms.Form):
# each field would be mapped as an input field in HTML
field_name = forms.Field(**options)

To create a form, in geeks/forms.py Enter the code,

Python
# import the standard Django Forms
# from built-in library
from django import forms 
  
# creating a form  
class InputForm(forms.Form): 
  
    first_name = forms.CharField(max_length = 200) 
    last_name = forms.CharField(max_length = 200) 
    roll_number = forms.IntegerField( 
                     help_text = "Enter 6 digit roll number"
                     ) 
    password = forms.CharField(widget = forms.PasswordInput()) 

To know more about how to create a Form using Django forms, visit How to create a form using Django Forms ?.

Render Django Forms

Django form fields have several built-in methods to ease the work of the developer but sometimes one needs to implement things manually for customizing User Interface(UI). A form comes with 3 in-built methods that can be used to render Django form fields. 

To render this form into a view, move to views.py and create a home_view as below. 

Python
from django.shortcuts import render
from .forms import InputForm

# Create your views here.
def home_view(request):
    context ={}
    context['form']= InputForm()
    return render(request, "home.html", context)

In view, one needs to just create an instance of the form class created above in forms.py. Now let’s edit templates > home.html 

html
<form action = "" method = "post">
    {% csrf_token %}
    {{form }}
    <input type="submit" value=Submit">
</form>

Now, visit http://localhost:8000/

create-django-form

. 
To check how to use the data rendered by Django Forms visit Render Django Form Fields 

Create Django Form from Models

Django ModelForm is a class that is used to directly convert a model into a Django form. If you’re building a database-driven app, chances are you’ll have forms that map closely to Django models. Now when we have our project ready, create a model in geeks/models.py,

Python
# import the standard Django Model
# from built-in library
from django.db import models
  
# declare a new model with a name "GeeksModel"
class GeeksModel(models.Model):
        # fields of the model
    title = models.CharField(max_length = 200)
    description = models.TextField()
    last_modified = models.DateTimeField(auto_now_add = True)
    img = models.ImageField(upload_to = "images/")
  
        # renames the instances of the model
        # with their title name
    def __str__(self):
        return self.title

To create a form directly for this model, dive into geeks/forms.py and Enter the following code:

Python
# import form class from django
from django import forms
 
# import GeeksModel from models.py
from .models import GeeksModel
 
# create a ModelForm
class GeeksForm(forms.ModelForm):
    # specify the name of model to use
    class Meta:
        model = GeeksModel
        fields = "__all__"

Now visit http://127.0.0.1:8000/, 

More on Django Forms:

Django Forms Data Types and Fields List

The most important part of a form and the only required part is the list of fields it defines. Fields are specified by class attributes. Here is a list of all Form Field types used in Django

NameClassHTML Input
BooleanFieldclass BooleanField(**kwargs)CheckboxInput
CharFieldclass CharField(**kwargs)TextInput
ChoiceFieldclass ChoiceField(**kwargs)Select
TypedChoiceFieldclass TypedChoiceField(**kwargs)Select
DateFieldclass DateField(**kwargs)DateInput
DateTimeFieldclass DateTimeField(**kwargs)DateTimeInput
DecimalFieldclass DecimalField(**kwargs)NumberInput when Field.localize is False, else TextInput
DurationFieldclass DurationField(**kwargs)TextInput
EmailFieldclass EmailField(**kwargsEmailInput
FileFieldclass FileField(**kwargs)ClearableFileInput
FilePathFieldclass FilePathField(**kwargs)Select
FloatFieldclass FloatField(**kwargs)NumberInput when Field.localize is False, else TextInput
ImageFieldclass ImageField(**kwargs)ClearableFileInput
IntegerFieldclass IntegerField(**kwargs)NumberInput when Field.localize is False, else TextInput
GenericIPAddressFieldclass GenericIPAddressField(**kwargs)TextInput
MultipleChoiceFieldclass MultipleChoiceField(**kwargs)SelectMultiple
TypedMultipleChoiceFieldclass TypedMultipleChoiceField(**kwargs)SelectMultiple
NullBooleanFieldclass NullBooleanField(**kwargs)NullBooleanSelect
RegexFieldclass RegexField(**kwargs)TextInput
SlugFieldclass SlugField(**kwargs)TextInput
TimeFieldclass TimeField(**kwargs)TimeInput
URLFieldclass URLField(**kwargs)URLInput
UUIDFieldclass UUIDField(**kwargs)TextInput

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 CharField 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:

Field OptionsDescription
requiredBy default, each Field class assumes the value is required, so to make it not required you need to set required=False
labelThe label argument lets you specify the “human-friendly” label for this field. This is used when the Field is displayed in a Form.
label_suffixThe label_suffix argument lets you override the form’s label_suffix on a per-field basis.
widgetThe widget argument lets you specify a Widget class to use when rendering this Field. See Widgets for more information.
help_textThe 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_messagesThe 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.
validatorsThe validators argument lets you provide a list of validation functions for this field. 
 
localizeThe 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. 
 


Previous Article
Next Article

Similar Reads

Styling Django Forms with django-crispy-forms
Django by default doesn't provide any Django form styling method due to which it takes a lot of effort and precious time to beautifully style a form. django-crispy-forms solves this problem for us. It will let you control the rendering behavior of your Django forms in a very elegant and DRY way. Modules required:django : django installdjango-crispy
1 min read
How to customize Django forms using Django Widget Tweaks ?
Django forms are a great feature to create usable forms with just few lines of code. But Django doesn't easily let us edit the form for good designs. Here, we will see one of the ways to customize Django forms, So they will look according to our wish on our HTML page. Basically we will check the methods to include our own custom css, classes, or id
3 min read
Render HTML Forms (GET & POST) in Django
Django is often called "Batteries Included Framework" because it has a default setting for everything and has features that can help anyone develop a website rapidly. Talking about forms, In HTML, a form is a collection of elements inside <form>...</form> that allow a visitor to do things like entering text, select options, manipulate o
5 min read
How to create a form using Django Forms ?
Django forms are an advanced set of HTML forms that can be created using python and support all features of HTML forms in a pythonic way. This post revolves around how to create a basic form using various Form Fields and attributes. Creating a form in Django is completely similar to creating a model, one needs to specify what fields would exist in
3 min read
{{ form.as_p }} - Render Django Forms as paragraph
Django forms are an advanced set of HTML forms that can be created using python and support all features of HTML forms in a pythonic way. Rendering Django Forms in the template may seem messy at times but with proper knowledge of Django Forms and attributes of fields, one can easily create excellent Form with all powerful features. In this article,
2 min read
{{ form.as_table }} - Render Django Forms as table
Django forms are an advanced set of HTML forms that can be created using python and support all features of HTML forms in a pythonic way. Rendering Django Forms in the template may seem messy at times but with proper knowledge of Django Forms and attributes of fields, one can easily create excellent Form with all powerful features. In this article,
2 min read
{{ form.as_ul }} - Render Django Forms as list
Django forms are an advanced set of HTML forms that can be created using python and support all features of HTML forms in a pythonic way. Rendering Django Forms in the template may seem messy at times but with proper knowledge of Django Forms and attributes of fields, one can easily create excellent Form with all powerful features. In this article,
2 min read
CharField - Django Forms
CharField in Django Forms is a string field, for small- to large-sized strings. It is used for taking text inputs from the user. The default widget for this input is TextInput. It uses MaxLengthValidator and MinLengthValidator if max_length and min_length are provided. Otherwise, all inputs are valid. CharField has following optional arguments: max
5 min read
BooleanField - Django Forms
BooleanField in Django Forms is a checkbox field which stores either True or False. It is used for taking boolean inputs from the user. The default widget for this input is CheckboxInput. It normalizes to: A Python True or False value. Syntax field_name = forms.BooleanField(**options) Django form BooleanField Explanation Illustration of BooleanFiel
5 min read
ChoiceField - Django Forms
ChoiceField in Django Forms is a string field, for selecting a particular choice out of a list of available choices. It is used to implement State, Countries etc. like fields for which information is already defined and user has to choose one. It is used for taking text inputs from the user. The default widget for this input is Select.It Normalizes
5 min read
TypedChoiceField - Django Forms
TypedChoiceField in Django Forms is a field just like ChoiceField, for selecting a particular choice out of a list of available choices. It is used to implement State, Countries etc. like fields for which information is already defined and user has to choose one. It is used for taking text inputs from the user. The default widget for this input is
5 min read
DateTimeField - Django Forms
DateTimeField in Django Forms is a date field, for taking input of date and time from user. The default widget for this input is DateTimeInput. It Normalizes to: A Python datetime.datetime object. It validates that the given value is either a datetime.datetime, datetime.date or string formatted in a particular datetime format. DateTimeField has one
5 min read
DateField - Django Forms
DateField in Django Forms is a date field, for taking input of dates from user. The default widget for this input is DateInput. It Normalizes to: A Python datetime.date object. It validates that the given value is either a datetime.date, datetime.datetime or string formatted in a particular date format. DateField has one optional arguments: input_f
5 min read
EmailField - Django Forms
EmailField in Django Forms is a string field, for input of Emails. It is used for taking text inputs from the user. The default widget for this input is EmailInput. It uses MaxLengthValidator and MinLengthValidator if max_length and min_length are provided. Otherwise, all inputs are valid. EmailField has following optional arguments: max_length and
5 min read
DurationField - Django forms
DurationField in Django Forms is used for input of particular durations for example from 12 am to 1 pm. The default widget for this input is TextInput. It Normalizes to: A Python datetime.date object. It validates that the given value is a string which can be converted into a timedelta. DurationField has one optional arguments: input_formats :- Acc
5 min read
DecimalField - Django Forms
DecimalField in Django Forms is a decimal field, for input of decimal numbers. The default widget for this input is NumberInput. It normalizes to a Python decimal. It uses MaxLengthValidator and MinLengthValidator if max_length and min_length are provided. Otherwise, all inputs are valid. DecimalField has following optional arguments: max_length an
5 min read
FileField - Django forms
FileField in Django Forms is a input field for upload of 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. It can validate that non-empty file data has been bound to the form. This article revolves about how to upload files with Dj
5 min read
FloatField - Django Forms
FloatField in Django Forms is a integer field, for taking input of floating point numbers from user. The default widget for this input is NumberInput.It normalizes to: A Python float. It validates that the given value is a float. It uses MaxValueValidator and MinValueValidator if max_value and min_value are provided. Leading and trailing whitespace
5 min read
FilePathField - Django Forms
FilePathField in Django Forms is a string field, for input of path of a particular file from server. It is used for select inputs from the user. One needs to specify which folders should be used in FilePathField and field displays the inputs in form of a select field. The default widget for this input is Select.FilePathField has following required
5 min read
TypedMultipleChoiceField - Django Forms
TypedMultipleChoiceField in Django Forms is a Choice field, for input of multiple pairs of values from a field and it includes a coerce function also to convert data into specific data types. The default widget for this input is SelectMultiple. It normalizes to a Python list of strings that you one can use for multiple purposes. TypedMultipleChoice
5 min read
MultipleChoiceField - Django Forms
MultipleChoiceField in Django Forms is a Choice field, for input of multiple pairs of values from a field. The default widget for this input is SelectMultiple. It normalizes to a Python list of strings which you one can use for multiple purposes. MultipleChoiceField has one required argument: choices :- Either an iterable of 2-tuples to use as choi
5 min read
GenericIPAddressField - Django Forms
GenericIPAddressField in Django Forms is a text field, for input of IP Addresses. It is field containing either an IPv4 or an IPv6 address. The default widget for this input is TextInput. It normalizes to a Python string. It validates that the given value is a valid IP address. GenericIPAddressField takes following optional arguments: protocol :- L
5 min read
ImageField - Django forms
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: Wh
6 min read
IntegerField - Django Forms
IntegerField in Django Forms is a integer field, for input of Integer numbers. The default widget for this input is NumberInput. It normalizes to a Python Integer. It uses MaxLengthValidator and MinLengthValidator if max_length and min_length are provided. Otherwise, all inputs are valid. IntegerField has following optional arguments: max_length an
5 min read
NullBooleanField - Django Forms
NullBooleanField in Django Forms is a select field which stores either True or False. It is used for taking boolean inputs from the user. The default widget for this input is NullBooleanSelect. It normalizes to: A Python True or False value. Syntax field_name = forms.NullBooleanField(**options) Django form NullBooleanField Explanation Illustration
5 min read
RegexField - Django Forms
RegexField in Django Forms is a string field, for small- to large-sized strings which one can match with a particular regular expression. It is used for taking selected text inputs from the user. The default widget for this input is TextInput. It uses MaxLengthValidator and MinLengthValidator if max_length and min_length are provided. Otherwise, al
5 min read
SlugField - Django Forms
SlugField in Django Forms is a slug field, for input of slugs for particular URLs or similar. This field is intended for use in representing a model SlugField in forms. The default widget for this input is TextInput. It uses validate_slug or validate_unicode_slug to validate that the given value contains only letters, numbers, underscores, and hyph
5 min read
TimeField - Django Forms
TimeField in Django Forms is a time input field, for input of time for particular instance or similar. The default widget for this input is TimeInput. It validates that the given value is either a datetime.time or string formatted in a particular time format. TimeField has following optional argument: input_formats :- A list of formats used to atte
5 min read
UUIDField - Django Forms
UUIDField in Django Forms is a UUID field, for input of UUIDs from an user. The default widget for this input is TextInput. It normalizes to: A UUID object. UUID, Universal Unique Identifier, is a python library that helps in generating random objects of 128 bits as ids. To know more about UUID visit Generating Random id’s using UUID in Python. Syn
5 min read
URLField - Django Forms
URLField in Django Forms is a URL field, for input of URLs from an user. This field is intended for use in representing a model URLField in forms. The default widget for this input is URLInput. It uses URLValidator to validate that the given value is a valid URL. Syntax field_name = forms.URLField(**options) Django form URLField Explanation Illustr
5 min read
Practice Tags :
three90RightbarBannerImg