Table of contents
1.
Introduction
2.
Django Form Fields
2.1.
Syntax
2.2.
Example
3.
How to use Django Forms
3.1.
Creating a Django Form
3.2.
Render Django Forms
3.3.
Create Django Form from Models
3.4.
Syntax:
4.
Basic Form Data Types and Fields
5.
Core Field Arguments
6.
Frequently Asked Questions
7.
Key Takeaways
Last Updated: Mar 27, 2024

Django forms fields

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The most crucial component of creating a Form class is defining the form's fields. Each field has its own set of validation rules, as well as a few other hooks. 

This article discusses the many fields that can be used in a form, as well as the various features and approaches associated with Django Forms. Forms are used to collect user input and use it to perform logical operations on databases. For example, the process of registering a user by taking input as his name, email, password, etc.

Django Form Fields

Django transforms Django form fields into HTML input fields. Django takes care of three main aspects of form work:

  • preparing and reorganizing data in preparation for rendering
  • creating HTML forms for the data
  • collection and processing client-submitted forms and data
     

It's worth noting that all of the work done by Django forms can be done with advanced HTML, but Django makes it easier and more efficient, particularly the validation aspect. Once you've mastered Django forms, you'll never go back to HTML forms.

Syntax

Django Fields are similar to Django Model Fields in that they have the following syntax:

field_name = forms.FieldType(**options)

Example

Following is a simple example of forms in Django

from django import forms

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

How to use Django Forms

To utilize Django Forms, you must first create a project and an app in it. You can construct a form in app/forms.py after you've started an app.

Creating a Django Form

In Django, building a form is quite similar to creating a model. The type of fields that would exist in the state must be specified. To fill out a registration form, for example, you might need to know your first name (CharField), your roll number (IntegerField), and so on.

Enter the code in ninjas/forms.py to build a form.

# 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())

Render Django Forms

Although Django form fields include various built-in methods to help developers, customizing the User Interface occasionally necessitates manual implementation (UI). A form has three built-in ways for rendering 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


Move to views.py and construct a home view below to render this form into a view.

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 

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

 

The output window at localhost would look like this:

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.

Syntax:

from django import forms
        
class FormName(models.Model):
         # each field would be mapped as an input field in HTML
        field_name = models.Field(**options)

 

Now when we have our project ready, create a model in ninjas/models.py,

# import the standard Django Model
# from built-in library
from django.db import models

 
# declare a new model with a name "GeeksModel"
class NinjasModel(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

 

Enter the following code in ninjas/forms.py to construct a form for this model directly:

# import form class from django
from django import forms

 
# import GeeksModel from models.py
from .models import NinjasModel

 
# create a ModelForm
class NinjasForm(forms.ModelForm):
# specify the name of model to use
class Meta:
model = NinjasModel
fields = "__all__"

Basic Form Data Types and Fields

The list of fields that a form defines is the most significant and only required portion of the form. Fields are specified via class attributes. 

The following is a list of all Django Form Field types.

Core Field Arguments

The arguments given to each field for applying a constraint or imparting a specific characteristic to that field are known as core Field arguments. 

If you give CharField core field argument required = False option, the user will be able to leave it blank. 

Each constructor of the Field class takes at least these arguments. Although some Field classes allow field-specific arguments. The following is a list of core field arguments.

Frequently Asked Questions

  1. Why do we use forms in Django?
    Django provides a Form class that is used to create HTML forms. It describes a form and how it works and appears. Each field of the form class map to the HTML form <input> element and each one is a class itself, it manages form data and performs validation while submitting the form.
     
  2. What is the difference between form and ModelForm in Django?
    The differences are that ModelForm gets its field definition from a specified model class, and also has methods that deal with saving of the underlying model to the database. A form is a common form that is unrelated to your database (model ).
     
  3. How many types of Django forms are there?
    Django form fields define two types of functionality, a form field's HTML markup and its server-side validation facilities.

Key Takeaways

The most crucial component of creating a Form class is defining the form's fields. Each field has its own set of validation rules, as well as a few other hooks.

Django transforms Django form fields into HTML input fields.

For more Django related blogs click the following links:

  1. for loop- Django template tags.
  2. Django email confirmation


Happy reading!!

Live masterclass