Prerequisites: Django Installation | Introduction to Django
Django works on an MVT pattern. So there is a need to create data models (or tables). For every table, a model class is created.
Suppose there is a form that takes Username, gender, and text as input from the user, the task is to validate the data and save it.
In django this can be done, as follows:
Python
from django.db import models
class Post(models.Model):
Male = 'M'
FeMale = 'F'
GENDER_CHOICES = (
(Male, 'Male' ),
(FeMale, 'Female' ),
)
username = models.CharField( max_length = 20 , blank = False ,
null = False )
text = models.TextField(blank = False , null = False )
gender = models.CharField(max_length = 6 , choices = GENDER_CHOICES,
default = Male)
time = models.DateTimeField(auto_now_add = True )
|
After creating the data models, the changes need to be reflected in the database to do this run the following command:
python manage.py makemigrations
Doing this compiles the models and if it didn’t find any errors then, it creates a file in the migration folder. Later run the command given below to finally reflect the changes saved onto the migration file onto the database.
python manage.py migrate
Now a form can be created. Suppose that the username length should not be less than 5 and post length should be greater than 10. Then we define the Class PostForm with the required validation rules as follows:
Python
from django.forms import ModelForm
from django import forms
from formValidationApp.models import *
class PostForm(ModelForm):
class Meta:
model = Post
fields = [ "username" , "gender" , "text" ]
def clean( self ):
super (PostForm, self ).clean()
username = self .cleaned_data.get( 'username' )
text = self .cleaned_data.get( 'text' )
if len (username) < 5 :
self ._errors[ 'username' ] = self .error_class([
'Minimum 5 characters required' ])
if len (text) < 10 :
self ._errors[ 'text' ] = self .error_class([
'Post Should Contain a minimum of 10 characters' ])
return self .cleaned_data
|
Till now, the data models and the Form class are defined. Now the focus will be on how these modules, defined above, are actually used.
First, run on localhost through this command
python manage.py runserver
Open http://localhost:8000/ in the browser, then it’s going to search in the urls.py file, looking for ‘ ‘ path
urls.py file is as given below:
Python
from django.contrib import admin
from django.urls import path, include
from django.conf.urls import url
from django.shortcuts import HttpResponse
from . import views
urlpatterns = [
path(' ', views.home, name =' index'),
]
|
Basically, this associates the ‘ ‘ url with a function home which is defined in views.py file.
views.py file:
Python
from .models import Post
from .forms import PostForm
from . import views
from django.shortcuts import HttpResponse, render, redirect
def home(request):
if request.method = = 'POST' :
details = PostForm(request.POST)
if details.is_valid():
post = details.save(commit = False )
post.save()
return HttpResponse( "data submitted successfully" )
else :
return render(request, "home.html" , { 'form' :details})
else :
form = PostForm( None )
return render(request, 'home.html' , { 'form' :form})
|
home.html template file
html
{% load bootstrap3 %}
{% bootstrap_messages %}
<!DOCTYPE html>
< html lang = "en" >
< head >
< title >Basic Form</ title >
< meta charset = "utf-8" />
< meta name = "viewport" content = "width=device-width, initial-scale=1, shrink-to-fit=no" >
</ script >
</ script >
</ head >
< body style = "padding-top: 60px;background-color: #f5f7f8 !important;" >
< div class = "container" >
< div class = "row" >
< div class = "col-md-4 col-md-offset-4" >
< h2 >Form</ h2 >
< form action = "" method = "post" >< input type = 'hidden' />
{%csrf_token %}
{% bootstrap_form form %}
<!-This is the form variable which we are passing from the function
of home in views.py file. That's the beauty of Django we
don't need to write much codes in this it'll automatically pass
all the form details in here
->
< div class = "form-group" >
< button type = "submit" class = "btn btn-default " >
Submit
</ button >
</ div >
</ form >
</ div >
</ div >
</ div >
</ body >
</ html >
|
Opening http://localhost:8000/ in the browser shows the following,

If a form with a username of length less than 5 is submitted, it gives an error at the time of submission and similarly for the Post Text filled as well. The following image shows how the form behaves on submitting invalid form data.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
23 Jan, 2023
Like Article
Save Article