Python Django Forms | Creating, Rendering, Validating and Saving Forms

In this tutorial, you’ll learn the Creating, Rendering, Validating and Saving Forms in Django.

Table of Contents

Introduction

WebForms provides an interactive way of communication between client and server. The client can access necessary information through these forms in return server processes this forms and responds by sending data requested by the client.

As a Software Developer, we normally write forms in HTML using <form> tag and then specify related field inside. This is a simple solution but the risk of validating data grows as the fields and complexity of form increases as Developers must validate data on the client-side as-well-as server-side which makes development process a headache.

Django Forms have come up with a solution for these type if unsafe form validation methods. These forms provide us with solutions from populating initial data, form fields wise validation, non-field validation and sanitizing unsafe values etc.

In this post we’ll be creating a simple form, render it to a template and save form values to tables.

Getting Started

Firstly, Create an app name it forms.

django-admin startapp forms

Add app path to installed apps section in settings.py file.

INSTALLED_APPS = [
    '...',
    '...',
    'forms.apps.FormsConfig',
]

In your projects, urls.py file create forms/urls.py file. So that we can access through route.

urlpatterns = [
    '...',
    '...',
    path('forms/', include('forms.urls'), name='forms'),
] 

In models.py create a Student Model.

from django.db import models

class Student(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=200)
    joining_date=models.DateField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table="students"
        verbose_name_plural="Students"

    def __str__(self): 
        return self.name

Creating Form Class

We start by creating a new forms.py file in forms app. We have import forms module.

from django import forms

class StudentProfile(forms.Form):
    name = forms.CharField(label="Student Name")
    joining_date = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'}))

The classStudentProfile inherits forms.Form class. Inside StudentProfile we are creating fields to our form.
For example name = forms.CharField(label="Student Name") creates a <input type="text" name="name" id="id_name" required> and joining_date = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'})) creates a <input type="date" name="joining_date" value="2019-02-21" id="id_joining_date"> the field in the template.

forms the module has fields.py file which describes field looks and type suppose forms.DateField() tell Django that it is a Date field and while validating to takes care of date format.

Calling Forms in Views

We have created our basic form and to render it to the template we must pass form class object as a parameter to the template and that we must do in views.py file.

from django.shortcuts import render,redirect
from django.http import HttpResponse,HttpResponseRedirect
from django.urls import reverse
from forms.forms import StudentProfile
from forms.models import Student

def example_one(request):
    context = {
        "form" : StudentProfile() # passing form with empty data.
    }
    template_name="forms/example_one.html"
    return render(request,template_name,context)

To call this function we need to import this to urls.py file in `forms` app.

from django.urls import path, include
from forms import views
from django.conf import settings
from django.conf.urls.static import static

app_name = 'forms' 
urlpatterns = [
    path('example_one', views.example_one, name='example_one'),
]

Rendering Form in Template

We create an HTML template in path forms/templates/forms/example_one.html.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Django Form Basics</title>
</head>
<body>
    <h1>Student Profile</h1>
    <form action="{% url 'forms:save_example_one' %}" method="post">
        {% csrf_token %}
        {{form}} <!-- rendering form fields inside <form> tag -->
        <div>
            <input type="submit" value="submit" >
        </div>
    </form>
</body>
</html>

Saving Form Data

In views.py create a function which saves submitted form data.

def save_example_one(request):
    form = StudentProfile(request.POST)

    if form.is_valid():
        query = {
            "name" : form.cleaned_data.get("name"),
            "joining_date" : form.cleaned_data.get("joining_date"),
            "course" : course,
        }
        student = Student.objects.create(**query)
        return HttpResponseRedirect(reverse('forms:example_one'))
    
    context = {
        "form" : form
    }
    
    template_name="forms/example_one.html"

    return render(request,template_name,context)

We pass POST data to StudentProfile() class this binds data to form. Calling form.is_valid() returns a Boolean value. If the form has validation errors than it returns false. We can get validation errors by calling form.errors() after the .is_valid() function.

Theform.cleaned_data.get("") returns sanitized data to submitted form using this method is recommended.

And create a route to submit the form in urls.py file.

    path('example_one/save', views.save_example_one, name='save_example_one'),

Note

Visit Official Django Documentation to learn more about Django forms

Conclusion

We have come to end of our post on Python Django Forms | Creating, Rendering, Validating and Saving Forms. We’ll be learning in-depth related to Django Forms such as Validation parts and Complex Forms in our next posts.

If you have any doubts please mention in the comments section and we’ll reach you soon and we would also love to hear requests and your recommendations for new tutorials/posts.

Related Posts

Summary
Review Date
Reviewed Item
Python Django Forms | Creating, Rendering, Validating and Saving Forms
Author Rating
51star
1star1star1star1star
Software Name
Django Web Framework
Software Name
Windows Os, Mac Os, Ubuntu Os
Software Category
Web Development