Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Render Django Form Fields Manually
Next article icon

Python | Form validation using django

Last Updated : 23 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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
 
# model named Post
class Post(models.Model):
    Male = 'M'
    FeMale = 'F'
    GENDER_CHOICES = (
    (Male, 'Male'),
    (FeMale, 'Female'),
    )
 
    # define a username field with bound  max length it can have
    username = models.CharField( max_length = 20, blank = False,
                                 null = False)
     
    # This is used to write a post
    text = models.TextField(blank = False, null = False)
     
    # Values for gender are restricted by giving choices
    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 *
 
# define the class of a form
class PostForm(ModelForm):
    class Meta:
        # write the name of models for which the form is made
        model = Post       
 
        # Custom fields
        fields =["username", "gender", "text"]
 
    # this function will be used for the validation
    def clean(self):
 
        # data from the form is fetched using super function
        super(PostForm, self).clean()
         
        # extract the username and text field from the data
        username = self.cleaned_data.get('username')
        text = self.cleaned_data.get('text')
 
        # conditions to be met for the username length
        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 any errors if found
        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):
 
    # check if the request is post
    if request.method =='POST': 
 
        # Pass the form data to the form class
        details = PostForm(request.POST)
 
        # In the 'form' class the clean function
        # is defined, if all the data is correct
        # as per the clean function, it returns true
        if details.is_valid(): 
 
            # Temporarily make an object to be add some
            # logic into the data if there is such a need
            # before writing to the database  
            post = details.save(commit = False)
 
            # Finally write the changes into database
            post.save() 
 
            # redirect it to some another page indicating data
            # was inserted successfully
            return HttpResponse("data submitted successfully")
             
        else:
         
            # Redirect back to the same page if the data
            # was invalid
            return render(request, "home.html", {'form':details}) 
    else:
 
        # If the request is a GET request then,
        # create an empty form object and
        # render it into the page
        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">
 
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
</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.
 

 



Next Article
Render Django Form Fields Manually

P

PortgasDAce
Improve
Article Tags :
  • Python
Practice Tags :
  • python

Similar Reads

  • Django Tutorial | Learn Django Framework
    Django, built with Python, is designed to help developers build secure, scalable, and feature-rich web applications quickly and efficiently. Whether you're a beginner looking to create your first dynamic website or an experienced developer aiming to enhance your skills, this tutorial will guide you
    11 min read
  • Django Basics

    • Django Basics
      Django is a Python-based web framework which allows us to quickly develop robust web application without much third party installations. It comes with many built-in features—like user authentication, an admin panel and form handling—that help you build complex sites without worrying about common web
      3 min read

    • Django Installation and Setup
      Installing and setting up Django is a straightforward process. Below are the step-by-step instructions to install Django and set up a new Django project on your system. Prerequisites: Before installing Django, make sure you have Python installed on your system. How to Install Django?To Install Djang
      2 min read

    • When to Use Django? Comparison with other Development Stacks
      Prerequisite - Django Introduction and Installation When to Use Django and Why? After getting to know the basics of Python, one should know when to use Django and why? Django is a high-level python based web framework which allows you to quickly create web applications without all of the installatio
      4 min read

    • Django Project MVT Structure
      Django is based on MVT (Model-View-Template) architecture. MVT is a software design pattern for developing a web application. MVT Structure has the following three parts - Model: The model is going to act as the interface of your data. It is responsible for maintaining data. It is the logical data s
      2 min read

    • How to Create a Basic Project using MVT in Django ?
      Prerequisite - Django Project MVT Structure Assuming you have gone through the previous article. This article focuses on creating a basic project to render a template using MVT architecture. We will use MVT (Models, Views, Templates) to render data to a local server. Create a basic Project: To initi
      2 min read

    • How to Create an App in Django ?
      Prerequisite - How to Create a Basic Project using MVT in Django? Django is famous for its unique and fully managed app structure. For every functionality, an app can be created like a completely independent module. This article will take you through how to create a basic app and add functionalities
      4 min read

    • Django settings file - step by step Explanation
      Once we create the Django project, it comes with a predefined Directory structure having the following files with each file having its own uses. Let's take an example // Create a Django Project "mysite" django-admin startproject mysite cd /pathTo/mysite // Create a Django app "polls" inside project
      3 min read

    Django view

    • Views In Django | Python
      Django Views are one of the vital participants of the MVT Structure of Django. As per Django Documentation, A view function is a Python function that takes a Web request and returns a Web response. This response can be the HTML contents of a Web page, a redirect, a 404 error, an XML document, an ima
      6 min read

    • Django Function Based Views
      Django is a Python-based web framework which allows you to quickly create web application without all of the installation or dependency problems that you normally will find with other frameworks. Django is based on MVT (Model View Template) architecture and revolves around CRUD (Create, Retrieve, Up
      7 min read

    • Django Class Based Views
      Django is a Python-based web framework that allows you to quickly create web applications. It has a built-in admin interface which makes it easy to work with it. It is often called a Class-Based included framework because it provides built-in facilities for every functionality. Class Based Generic V
      10 min read

    • Class Based vs Function Based Views - Which One is Better to Use in Django?
      Django...We all know the popularity of this python framework all over the world. This framework has made life easier for developers. It has become easier for developers to build a full-fledged web application in Django. If you're an experienced Django developer then surely you might have been aware
      7 min read

  • Django Templates
    Templates are the third and most important part of Django's MVT Structure. A template in Django is basically written in HTML, CSS, and Javascript in a .html file. Django framework efficiently handles and generates dynamic HTML web pages that are visible to the end-user. Django mainly functions with
    7 min read
  • Django Static File
    Static Files such as Images, CSS, or JS files are often loaded via a different app in production websites to avoid loading multiple stuff from the same server. This article revolves around, how you can set up the static app in Django and server Static Files from the same.Create and Activate the Virt
    3 min read
  • Django Model

    • Django Models
      A Django model is the built-in feature that Django uses to create tables, their fields, and various constraints. In short, Django Models is the SQL Database one uses with Django. SQL (Structured Query Language) is complex and involves a lot of different queries for creating, deleting, updating, or a
      10 min read

    • Django model data types and fields list
      The most important part of a model and the only required part of a model is the list of database fields it defines. Fields are specified by class attributes. Be careful not to choose field names that conflict with the models API like clean, save, or delete. Example: from django.db import models clas
      4 min read

    • Built-in Field Validations - Django Models
      Built-in Field Validations in Django models are the default validations that come predefined to all Django fields. Every field comes in with built-in validations from Django validators. For example, IntegerField comes with built-in validation that it can only store integer values and that too in a p
      3 min read

    • How to use User model in Django?
      The Django’s built-in authentication system is great. For the most part we can use it out-of-the-box, saving a lot of development and testing effort. It fits most of the use cases and is very safe. But sometimes we need to do some fine adjustment so to fit our Web application. Commonly we want to st
      3 min read

    • Meta Class in Models - Django
      Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. It’s free and open source. D
      3 min read

    • get_object_or_404 method in Django Models
      Some functions are hard as well as boring to code each and every time. But Django users don't have to worry about that because Django has some awesome built-in functions to make our work easy and enjoyable. Let's discuss get_object_or_404() here. What is get_object_or_404 in Django?get_object_or_404
      2 min read

    Django Forms

    • Django Forms
      When one creates a Form class, the most important part is defining the fields of the form. Each field has custom validation logic, along with a few other hooks. This article revolves around various fields one can use in a form along with various features and techniques concerned with Django Forms. D
      6 min read

    • How to create a form using Django Forms ?
      Django forms are an advanced set of HTML forms that can be created using python and support all features of HTML forms in a pythonic way. This post revolves around how to create a basic form using various Form Fields and attributes. Creating a form in Django is completely similar to creating a model
      3 min read

    • Django Form | Data Types and Fields
      When gathering user information to store in a database, we employ Django forms. Django offers a variety of model field forms for different uses, and these fields have a variety of patterns. The fact that Django forms can handle the fundamentals of form construction in just a few lines of code is the
      6 min read

    • Django Form | Build in Fields Argument
      We utilize Django Forms to collect user data to put in a database. For various purposes, Django provides a range of model field forms with various field patterns. The most important characteristic of Django forms is their ability to handle the foundations of form construction in only a few lines of
      3 min read

    • Python | Form validation using django
      Prerequisites: Django Installation | Introduction to DjangoDjango 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 th
      5 min read

    • Render Django Form Fields Manually
      Django form fields have several built-in methods to ease the work of the developer but sometimes one needs to implement things manually for customizing User Interface(UI). We have already covered on How to create and use a form in Django?. A form comes with 3 in-built methods that can be used to ren
      5 min read

    Django URLS

    • Django URL patterns | Python
      Prerequisites: Views in Django In Django, views are Python functions which take a URL request as parameter and return an HTTP response or throw an exception like 404. Each view needs to be mapped to a corresponding URL pattern. This is done via a Python module called URLConf(URL configuration) Let t
      2 min read

    • Get parameters passed by urls in Django
      Django is a fully fleshed framework which can help you create web applications of any form. This article discusses how to get parameters passed by URLs in django views in order to handle the function for the same. You might have seen various blogs serving with urls like: - www.example.com/articles/9
      2 min read

    • url - Django Template Tag
      A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to template, but also provides some
      3 min read

    • URLField - Django Models
      URLField is a CharField, for a URL. It is generally used for storing webpage links or particularly called as URLs. It is validated by URLValidator. To store larger text TextField is used. The default form widget for this field is TextInput. Syntax field_name = models.URLField(max_length=200, **optio
      4 min read

    • URL fields in serializers - Django REST Framework
      In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_n
      5 min read

  • Python | Django Admin Interface
    In this article, we delve into the capabilities and advantages of the Django Admin Interface, exploring how its customizable features and streamlined workflows empower developers to effortlessly administer their projects, from data management to user interactions. Prerequisites: django-introduction-
    4 min read
  • More topics on Django

    • Handling Ajax request in Django
      Introduction This tutorial explains how to carry out an ajax request in the Django web framework. We will create a simple post-liking app as a part of the example. Glossary Project InitializationCreate modelsCreate viewsWrite URLsCarry out a request with Jquery Ajax.Register models to admin and add
      4 min read

    • Python | User groups with Custom permissions in Django
      Let's consider a trip booking service, how they work with different plans and packages. There is a list of product which subscriber gets on subscribing to different packages, provided by the company. Generally, the idea they follow is the level-wise distribution of different products. Let's see the
      4 min read

    • Python | Django Admin Interface
      In this article, we delve into the capabilities and advantages of the Django Admin Interface, exploring how its customizable features and streamlined workflows empower developers to effortlessly administer their projects, from data management to user interactions. Prerequisites: django-introduction-
      4 min read

    • Python | Extending and customizing django-allauth
      Prerequisite: Django-allauth setup and Configuration Let's deal with customizing django-allauth signup forms, and intervening in registration flow to add custom processes and validations. Extending the Signup Form or adding custom fields in Django-allauth: One of the most common queries about allaut
      4 min read

    • Django - Dealing with warnings
      Prerequisite : Django - Creating project Django is a great framework which provides you a lot of pre-defined services and workflow so that one can work flawlessly. Django apps are designed to make your code clean and reusable. Django works on the concept of DRY which means Don't Repeat Yourself. Aft
      2 min read

    • Python | Sessions framework using django
      The sessions framework can be used to provide persistent behavior for anonymous users on the website. Sessions are the mechanism used by Django for you to store and retrieve data on a per-site-visitor basis. Django uses a cookie containing a unique session ID. Django SessionsSo let's understand what
      4 min read

    • Django Sign Up and login with confirmation Email | Python
      Django by default provides an authentication system configuration. User objects are the core of the authentication system. Today we will implement Django's authentication system. Modules required: Django install, crispy_forms Django Sign Up and Login with Confirmation EmailTo install crispy_forms yo
      7 min read

geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences