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 Create Superuser

For managing the website, we need an Admin while creating the Django application. In order to create the admin user, create superuser command is used. The superuser is called the...

3 minutes read.

How to Implement Multiple User Types with Django

Django Framework: 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...

3 minutes read.

Life Cycle of Django

Life Cycle of Django Request - Response life cycle in Django  Thebasic principle of http protocol is the client sends a request to the server based on the request data, and the server sends...

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.

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.

Features of Django

Features of Django Offers High Security:- Django is super secure. To prove the feature, we can always take examples of lots of websites which are present worldwide and possess huge traffic. Django is secure because it covers the...

3 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 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 Environment Setup

Django is a free and open-source web framework, which uses Python as its programming language. It is based on Model View Template (MVT) architecture. A framework is a collection of...

4 minutes read.

Uses of Django

Django is a free and open-source Python-based web framework, which offers great functionalities to its users. Django was developed in 2003, and the final version was released in 2008 by...

3 minutes read.

What is Django?

What is Django? Django is a free and open-source web application framework, written in Python. A web framework is a set of components that help you develop an easier and faster website. When we...

3 minutes read.

Django All Auth

For any web application, user registration and authentication are the essential parts. In Django, there are several applications like django-registration-redux to perform these tasks, but the major drawback is that...

6 minutes read.

Django Project

Django Project Let's start to use it. Each web app you want to build in Django is called a project; and a project is a collection of apps. A software is a series of...

3 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 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 CSRF

Django is a high-level python based web framework. Django is open source and free to use for all. Django provides many features to web developers like scalability, security, rapid development,...

4 minutes read.

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 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.

Django CMS

Django is one of the most popular open-source Python web development framework. Developers use Django to build a website from scratch. Like WordPress, Django CMS is also a Content Management...

9 minutes read.

Django Create App

Django is a Python-based web framework that is based on the Model View Template architecture. In this post, we will go through the installation and setup for our first Django...

4 minutes read.