Django Form Validation cleaned_data Example

Published On: 29/09/2022 | Category: Django

Hi Dev,

In this tutorial, I will show you django form validation cleaned_data example. let’s discuss about django form cleaned_data. This article will give you simple example of django form validation before submit. In this article, we will implement a django form validation example. Follow bellow tutorial step of how to use cleaned_data form validation in django.

A field's validate is checked using the cleaned_data. In essence, whatever data submitted into a form will be delivered as strings to the server. Which type of form field was used when the form was created is irrelevant. The browser would ultimately convert everything to strings.

Let's see bellow example I explained simply about django form cleaned_data validation example.

Step 1: Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject exampleapp

Step 2: Create a App

Now we'll create a single app called polls to store a list of post names. We're keeping things intentionally basic. Stop the local server with Control+c and use the startapp command to create this new app.

python3 manage.py startapp core

Step 3: Update setting.py

Next, In this step we require to do two things in our settings.py file, One is our installed app name Add the below lines to your settings.py file:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'core',
]

Step 4: Create a Form

First of all in this step we will create a new file called forms.py and create a Django form you need to use Django Form Class

core/forms.py
from django import forms

class EmpDetailsForm(forms.Form):
    name=forms.CharField(
        max_length=100,
        widget=forms.TextInput(attrs={
            'class': 'form-control'
    }))
    email=forms.EmailField(
        label='Email',
        widget=forms.TextInput(attrs={
        'class': 'form-control'
    }))
    contact=forms.CharField(
        widget=forms.TextInput(attrs={
        'class': 'form-control'
    }))

Step 5: Creating the Views

In this step, we need to create the views for performing the post request data is to cleaned to cleaned_data method.Open the core/views.py file and add:

core/views.py
from django.shortcuts import render
from .forms import EmpDetailsForm

def emp_form(request):
    if request.method == "POST":  
        form = EmpDetailsForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            email = form.cleaned_data['email']
            contact = form.cleaned_data['contact']
            return render(request,'core/form.html',{'form':form,'name':name,'email':email,'contact':contact})  

    else:
        form =EmpDetailsForm()
    return render(request,'form.html',{'form':form})  

Step 6: Creating the Templates

Next, open the core/templates/form.html file and the add:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Tuts-Station.com</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
    <style type="text/css">
        body{
            background-color: #f7fcff;
        }
    </style>
</head>
<body>
    <div class="container mt-5">
        <div class="row d-flex justify-content-center">
            <div class="col-md-10">
                <div class="card">
                    <div class="card-header">
                        <h3>Django Form cleaned_data Validation Example - <span class="text-primary">Tuts-Station.com</span></h3>
                    </div>
                    <div class="card-body">
                        <form method = "post" enctype="multipart/form-data">
                            {% csrf_token %}
                            {{ form.as_p }}
                            <button type="submit" class="btn btn-success">Submit</button>
                        </form>
                        <div class="row mt-3">
                            <div class="col-md-12">
                                {% if name %}
                                    <p>Name : {{name}}</p>
                                    <p>Email : {{email}}</p>
                                    <p>Contact : {{contact}}</p>
                                {% endif %}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

Step 7: Creating Urls

In this section, we’ll create the urls to access our views.Go to the urls.py core/urls.py file and update it as follows:

core/urls.py
from django.urls import path, include
from . import views

urlpatterns = [
    path('form', views.emp_form),
]

Next, we will require the modify the urls.py your root preoject folder lets update the file.

exampleapp/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('core.urls')),
]

Run the Server

In this step, we’ll run the local development server for playing with our app without deploying it to the web.

python manage.py runserver

Next, go to the url address bar with a web browser.

http://localhost:8000/form

I Hope It will help you....