Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

django
python
communitycreator

How to do Django form validation

Njoku Ifeanyi Gerald

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 HTMLHyperText Markup Language forms, except that they are more Python-oriented in nature.

Code

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

Configurations

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'
]
settings.py

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 Post
class 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)
models.py

Once our model is created, register it in the admin.py file, as shown below:

from django.contrib import admin
from .models import CommentModel

admin.site.register(CommentModel)
admin.py

Create the form

After completing the configuration, create a file for the form. In our case, the file is named forms.py.

from logging import PlaceHolder
from django import forms
from .models import CommentModel

class 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 = CommentModel
        fields = ['name', 'comment']

   

    def clean(self):
        # data is feteched using the super function of django
        super(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

forms.py

Now, create a view for our project with the form created. The corresponding views.py file is shown below:

from django.shortcuts import render, redirect
from .models import CommentModel
from .forms import CommentForm


def 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)
  • Next, in the codebase app folder, create a folder and name it templates.
  • Inside the templates folder, create another folder and name it app.
  • Inside the 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>
home.html

Set route URLs

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 admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    # including the codebase urls.py file
    path('', 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.py
from .views import home


urlpatterns = [
    path('', home, name='home'),
]

Access form

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.

RELATED TAGS

django
python
communitycreator

CONTRIBUTOR

Njoku Ifeanyi Gerald
RELATED COURSES

View all Courses

Keep Exploring