Django Form Validation Example
Hi Dev,
This article will provide some of the most important example django python form validation example. I explained simply about how to add form validation in python django. Here you will learn django field validation example. Here you will learn django python form validation error example..
Let's see bellow example I explained simply about django field validation example.
Table of Contents
- Create a Project
- Create an App
- Database Setup
- Create a Model
- Create a FormClass
- Creating the Views
- Creating the Templates
- Creating Urls
- Run the Server
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
Create an App
python3 manage.py startapp contactForm
Next, you need to add it in the settings.py file as follows:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'contactForm',
]
Database Setup
Next step, we will modify the settings.py file and update the smtp email backends settings to configure:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'example',
'USER':'root',
'PASSWORD':'root',
'HOST':'localhost',
'PORT':'3306'
}
}
Create a Model
In this step. we will require the database model for storing contacts.Open the contactForm/models.py file and add the following code:
from django.db import models
class Contact(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
contact = models.CharField(max_length=100)
Create a FormClass
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
from django.forms import ModelForm
from django import forms
from core.models import Contact
class ContactForm(forms.ModelForm):
name = forms.CharField(max_length=100,
required=True,
widget=forms.TextInput(attrs={'placeholder': 'Name',
'class': 'form-control',
}))
email = forms.EmailField(required=True,
widget=forms.TextInput(attrs={'placeholder': 'Email',
'class': 'form-control',
}))
contact = forms.CharField(required=True,
widget=forms.TextInput(attrs={'placeholder': 'Contact',
'class': 'form-control',
}))
class Meta:
model = Contact
fields = "__all__"
Creating the Views
In this step, we need to create the views for performing fetch records to the database. Open the contactForm/views.py file and add:
from django.shortcuts import render, redirect
from .forms import ContactForm
def contactForm(request):
if request.method == "POST":
form = ContactForm(request.POST)
if form.is_valid():
try:
return redirect('contact')
except:
pass
else:
form = ContactForm()
return render(request,'contact.html',{'form':form})
Creating the Templates
Next, open the contactForm/templates/index.html file and the add:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Django Form Validation Example</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-5 pt-5">
<div class="row d-flex justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">
<h3>Django Form Validation Example - <span class="text-primary">Tuts-Station.com</span></h3>
</div>
<div class="card-body">
<form method="POST" novalidate>
{% csrf_token %}
<div class="form-row">
<div class="col-md-12">
<div class="form-group">
<label class="small mb-1">Name:</label>
{{ form.name }}
<small class="text-danger">{{ form.errors.name|striptags }}</small>
</div>
</div>
</div>
<div class="form-row">
<div class="col-md-12">
<div class="form-group">
<label class="small mb-1">Email:</label>
{{ form.email }}
<small class="text-danger">{{ form.errors.email|striptags }}</small>
</div>
</div>
</div>
<div class="form-row">
<div class="col-md-12">
<div class="form-group">
<label class="small mb-1">Contact:</label>
{{ form.contact }}
<small class="text-danger">{{ form.errors.contact|striptags }}</small>
</div>
</div>
</div>
<div class="form-group mt-2 mb-0">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Creating Urls
In this section, we’ll create the urls to access our views.Go to the urls.py contactForm/urls.py file and update it as follows:
from django.urls import path
from . import views
urlpatterns = [
path('contact-us', views.contactForm, name='contact'),
]
Next, we will require the modify the urls.py your root preoject folder lets update the file.
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('contactForm.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/contact-us
I Hope It will help you.