Django Forms - GeeksforGeeks

12 Jan, 2022
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. Forms are basically 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 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
Note that all types of work done by Django forms can be done with advanced HTML stuff, but Django makes it easier and efficient especially the validation part. Once you get hold of Django forms 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:
Python3
from django import forms # creating a formclass GeeksForm(forms.Form):    title = forms.CharField()    description = forms.CharField()
To use Django Forms, 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. 
How to Create a Basic Project using MVT in Django?
How to Create an App 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,
Python3
# import the standard Django Forms# from built-in libraryfrom 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 ?.
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. 
{{ form.as_table }} will render them as table cells wrapped in <tr> tags
{{ form.as_p }} will render them wrapped in <p> tags
{{ form.as_ul }} will render them wrapped in <li> tags
To render this form into a view, move to views.py and create a home_view as below. 
Python3
from django.shortcuts import renderfrom .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/
. To check how to use the data rendered by Django Forms visit Render Django Form Fields 
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,
Python3
# import the standard Django Model# from built-in libraryfrom 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:
Python3
# import form class from djangofrom django import forms  # import GeeksModel from models.pyfrom .models import GeeksModel  # create a ModelFormclass GeeksForm(forms.ModelForm):    # specify the name of model to use    class Meta:        model = GeeksModel        fields = "__all__"
Now visit http://127.0.0.1:8000/, 
Render HTML Forms (GET & POST) in Django
{{ form.as_p }} – Render Django Forms as paragraph
{{ form.as_table }} – Render Django Forms as table
{{ form.as_ul }} – Render Django Forms as list
Django form field custom widgets
Python | Form validation using django
Django ModelForm – Create form from Models
Render Django Form Fields Manually
Django Formsets
Django ModelFormSets
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
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:
.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; }
ddeevviissaavviittaa
RajuKumar19
Django-forms
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
How to Install PIP on Windows ?
Enumerate() in Python
Read a file line by line in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string