Django Forms

Django is a Python Programming Open Source framework for web development. It was released in 2008 and was developed by two web developers named Adrian Holovaty and Simon Willison. It uses Model View Template architecture. It is mighty. Django is used by some of the biggest companies in the world as their backend framework. 

It is a high-speed and secure framework with some great libraries that save the user from creating an application from scratch. It can be implemented in various frameworks such as HTML, JSON, XML, etc. Django can be used in ORM, ML integration, API integration, etc. 

While building a website in Django, if we are taking input from the users, we will need to use forms. It is very easy to create forms with Django. Django provides a Form class that is used to create form. Building forms in Django is very similar to creating a model.  Like the model, while creating the form, the most important part is creating the field. Each field has a data type that validates the data inputted by the user.

Form Handling in Django

Form Handling is not an easy task for a programmer to do. When a user inputs the data in a form, Django maps it to the corresponding field. Django does all this form handling on our behalf. Django's form handling can be divided into three distinct parts:

  • Django processes the data to make it ready for rendering.
  • Django creates an HTML form for the data.
  • Django also receives and processes submitted forms by the users.

Django Form Class

Django created the form using the form class. The Form class decides the overall functioning of the form. It describes the forms and the fields that form has. The Form class is similar to the model in mapping the data. The model class maps the data with the database table, and the form class maps it to HTML form elements.

Syntax:

field = forms.FieldType(**options) 

Building Forms

To create a form, we need to instantiate a project first. To start your Django project, activate your virtual environment and run the following command:

django-adminstartprojectmyproject

After creating the project, we need to create an app too successfully.

In this post, we will create a student form in Django. In this form, we will create the fields for first name and roll number. The first name will be Garfield, and the roll number will be the Integer field. Just like the other important applications, we will create a separate file for forms. So add a forms.py file in myproject folder. Write the below code in the file:

fromDjango importforms 
    
# creating a form  
classStudent_Form(forms.Form): 
    
    first_name =forms.CharField(max_length =200) 
    roll_number =forms.IntegerField( ) 

The above code defines the form with two fields. The max_length argument constrains the maximum length of the input field. It also makes Django validates the length of the input. The form uses a method is_valid() to validates the data for all the fields. This method will return True if all the data is validated and place it in its cleaned_dataattribute.

The following HTML will be rendered for the above form:

<label for=" first_name">Enter first name:</label>  
 <input type="text" name=" first_name" required maxlength="200" id=" first_name" />  
<label for = “roll_number”> Enter roll number: </label>
<input type = “integer” name = “roll_number” id = “roll_number”/>

A Django form field can be rendered by 3 built-in methods of forms:

  • {{ form.as_table }} rendered as table cells wrapped in <tr> tags
  • {{ form.as_p }} rendered as  wrapped in <p> tags
  • {{ form.as_ul }} rendered as  wrapped in <li> tags

Now we need to instantiate the form in the views.py file to render the form. Use this code in your views.py file:

fromDjango.shortcuts import render
from .forms import InputForm


defstudent_view(request):
    context ={}
    context['form']= InputForm()
    return render(request, "index.html", context)

Now we need to pass the context in to the template:

Index.html

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

Now we are done with creating the form. Open your browser and navigate to the localhost to see the form:

Django Forms

Form Fields

NameClassHTML Input
BooleanFieldclass BooleanField(**kwargs)CheckboxInput
CharFieldclass CharField(**kwargs)TextInput
ChoiceFieldclass ChoiceField(**kwargs)Select
DateFieldclass DateField(**kwargs)DateInput
DateTimeFieldclass DateTimeField(**kwargs)DateTimeInput
DecimalFieldclass DecimalField(**kwargs)NumberInput
EmailFieldclass EmailField(**kwargs)EmailInput
FileFieldclass FileField(**kwargs)ClearableFileInput
ImageFieldclass ImageField(**kwargs)ClearableFileInput

Related Topics

Django Stack

Django is a popular Python web application framework that adheres to the "batteries-included" tenet. Batteries-guiding included idea is that common functionality for creating web applications should be provided with the...

5 minutes read.

Django Frontend

Django Django is a framework that can make web applications more accessible and faster. Django is an open-source collection of python libraries, and Django can be used for both the front...

3 minutes read.

Django Installation

Django Installation Django development environment consists of installing and setting up Python, Django, and a Database System since Django deals with a web application. Below the statement will guide you through installing Python 3.8.0 and...

2 minutes read.

Django Tutorial

Django Introduction It is a web application framework written in a python programming language. It based on the MVT( Model View Templet) design pattern. It takes a short time to build an application...

2 minutes read.

Django Filters

Django is a high-level python based web framework. Django is mostly used as a backend engine for websites. Nowadays, every website communicates to a database to fetch all the information...

3 minutes read.

Django Create Project

Django is an open-source free to use web framework which is based on Python. Django uses Model-View-Template as its architecture. The final version of Django was released in 2008. Django...

4 minutes read.

Django Model Fields

In Django, if we want to store the information about anything, we use Models. It contains various fields about the data. Generally, each model represents a database where all the...

4 minutes read.

Django vs Laravel

Django Overview Django is a Python Programming Open Source framework for web development. It was released in 2008 and was developed by two web developers named Adrian Holovaty and Simon Willison....

4 minutes read.

Django Template System

Django Template System Django allows Python and HTML to be divided, the Python goes into views, and HTML goes into templates. Django relies on the render feature and the language of the Django Model...

5 minutes read.

Django Forms

Django is a Python Programming Open Source framework for web development. It was released in 2008 and was developed by two web developers named Adrian Holovaty and Simon Willison. It...

3 minutes read.

Django Class Based Views

Class-based views were developed to solve the problem of customizing function-based generic views. We can arrange our view code Object-Oriented by using class views. Class-based views do more than function-based...

3 minutes read.

Django Logging

Every application developed has some bugs and errors. It is the responsibility of the developers to maintain the application by making it bug-free and error-free. To debug the application code...

5 minutes read.

Django Image Upload

Django is a python based web framework that uses Model View Template as its architecture. Django provides really quick web development with its functionalities. While we are building a website,...

3 minutes read.

Django MVT

 MVT(Model View Template) MVT means Model View Template is a software design pattern The View is used to implement the business logic and to communicate with a model for data transmission and to...

2 minutes read.

How to connect Django with Mysql

Any web application contains some data that comes from the input of the end-users. Thus, the database is required to handle those data. Several databases could be used to connect...

3 minutes read.

Creating View in Django

Creating View in Django    Django views are a key component of the frameworkbased applications.We are using Python function or class at their simplest, which takes up a web query and returns a web response.Views are used to get objects from the server, change objects if needed, render types, return HTML, and much more. Class Based View and Function based Django has two types of views: views based on functions (FBVs) and views based on class (CBVs).Initially, Django began with only FBVs, but then introduced CBVs as a way to model features so we didn't have to write boilerplate (i.e. the same software) code again and again.CBVs would be a way to increase efficiency, so you don't have to write as much code as you can. CBVs are classes of Python at their heart. Django ships with a range of "model" CBVs with pre-configured features that can be reused and often expanded.Then helpful names are given to these classes that explain what kind of functionality they provide.These are often referred to as "universal views" because they provide solutions to specific needs. The classes have a journal View function, or "view" for short, is simply a Python program that uses a web query and returns a web response. This response may include the HTML content of a web page, or a redirect, or a 404 error, or an XML file, or an image, etc. Example: You use a view to create a web page, remember that you need to connect a view to a URL to see it as a web page. Simple View We will create a simple view in myapplication to say “Welocome to django application” See the following view – from django.http import HttpResponse ...

4 minutes read.

Django Channels

Channels is a project that uses Django and adds some functionalities beyond the traditional HTTP by using WSGI and ASGI.  We can use both synchronous and asynchronous requests with ASGI...

5 minutes read.

Django Admin

To manage the content of the website, e.g., adding and deleting posts, web developers need an admin portal on the website. The admin portal allows trusted users, also knows as...

3 minutes read.

Django Celery

Django is a python-based web framework. It is an open-source and free-to-use framework. Django uses the Model View Template architecture. Django provides many functionalities to web developers. One of these...

3 minutes read.

Django CMS vs WordPress

Both Django CMS and WordPress belong "Self-Hosted Blogging" or "Content Management System (CMS)" category, that is used to manage digital content. Bloggers usually use these platforms. Django CMS Django is one of...

4 minutes read.