In this shot, we’ll learn to do Django form validation. Django automatically has built-in methods that validate the data from the form.
Note: Django forms are similar to advanced
forms, except that they are more Python-oriented in nature. HTML HyperText Markup Language
First, install Django by using the following commands:
pip install pipenv
pipenv shell
pipenv install django
Next, create the Django project:
django-admin startproject DjangoForm ./
python manage.py startapp codebase
python manage.py migrate
python manage.py runserver
First, add the project name to the settings.py
file, as shown below:
INSTALLED_APPS = ['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','codebase']
Note:
codebase
should be replaced by the name of your Django project.
Next, in the codebase
application folder, go to the models.py
file and create the following model:
from django.db import models# model named Postclass CommentModel(models.Model):name = models.CharField( max_length = 100, blank = False,null = False)comment = models.TextField(blank = False, null = False)time = models.DateTimeField(auto_now_add = True)
Once our model is created, register it in the admin.py
file, as shown below:
from django.contrib import adminfrom .models import CommentModeladmin.site.register(CommentModel)
After completing the configuration, create a file for the form. In our case, the file is named forms.py
.
from logging import PlaceHolderfrom django import formsfrom .models import CommentModelclass CommentForm(forms.ModelForm):name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control','placeholder': 'name'}))comment = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control','placeholder': 'comment section'}))class Meta:model = CommentModelfields = ['name', 'comment']def clean(self):# data is feteched using the super function of djangosuper(CommentForm, self).clean()name = self.cleaned_data.get('name')comment = self.cleaned_data.get('comment')if len(name) < 3:self._errors['name'] = self.error_class(['3 characters and more is required for this field'])if len(comment) < 4:self._errors['comment'] = self.error_class(['comments should be more than 4 characters'])return self.cleaned_data
Now, create a view for our project with the form created. The corresponding views.py
file is shown below:
from django.shortcuts import render, redirectfrom .models import CommentModelfrom .forms import CommentFormdef home(request):form = CommentForm(request.POST or None)if request.method == 'POST':if form.is_valid():form.save()return redirect ('home')context = {'form': form}return render(request, 'app/home.html', context)
codebase
app folder, create a folder and name it templates
.templates
folder, create another folder and name it app
.app
folder, create the home.html
file as shown below:<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"crossorigin="anonymous"></head><body class="container mt-4"><form method="POST" action="">{% csrf_token %}<div class="form-group mb-3">{{form.name}}{{form.name.errors}}</div><div class="form-group mb-3">{{form.comment}}{{form.comment.errors}}</div><button class="btn btn-outline-success">Submit</button></form></body></html>
Within the main folder, in the urls.py
file, add a route to the URLs of the codebase
app, as shown below:
from django.contrib import adminfrom django.urls import path, includeurlpatterns = [path('admin/', admin.site.urls),# including the codebase urls.py filepath('', include('codebase.urls'))]
Finally, in the codebase folder, create a file called urls.py
that contains the route to the home
view:
from django.urls import path#importing home function from views.pyfrom .views import homeurlpatterns = [path('', home, name='home'),]
Once the entry process is complete, run the following commands:
python manage.py makemigrations
python manage.py migrate
In case you want to create a super-user, run the following command:
python manage.py createsuperuser
Once we’re ready to access the newly created form, run this command:
python manage.py runserver
The command above starts our server on the URL: http://127.0.0.1:8000/admin
, which can be accessed now.