How to Present Error Message in the Form in Django

Posted on

Introduction

This article is focusing on how to describe in more detail about the explanation on the previous article. That article is an article with the title of ‘How to Display Form Error in Django’ in this link. So, this article not only will renew all the information on that article but also will add other necessary information. So, before going through the steps for demonstrating the Django application, there are descriptions about the project conditions. Those descriptions are about the Django project itself. The base Django-based web application is referring to the article with the title of ‘How to Use Crispy Form Tag in Django by Using a Form’ in this link.

Present Error Message in the Form in Django Application

Before getting in to the demonstration of presenting error in the Django application, there are several information regarding the base application. Those are the basic pre-requirement, settings and configuration before going in deep to the modification of the application. The modification will show a specific information about presenting the error message in a form.

Preparing the environment for installing Django Module

  1. First of all, the existance of ‘python’ program or binary executable. Type ‘python’ in the command line to check the existance. Read the article with the title of ‘How to Install Python in Linux CentOS 8 virtual server running in VirtualBox Application’ in this link. It is just an article for a reference. The following is the execution of the command ‘python’ for retrieving the version of the python used in this example :

    Microsoft Windows [Version 10.0.19042.1165]
    (c) Microsoft Corporation. All rights reserved.
    
    C:\Users\Personal>python --version
    Python 3.8.2
    
    C:\Users\Personal>
    
  2. Next, the existance of ‘pip’ program or binary executable. Type ‘pip’ in the command line to check the existance. Read the article with the title of ‘How to Install pip tool for Managing Package in Ubuntu Linux 18.04’ in this link. Either way, just make sure to install ‘pip’. Find other articles for pip installation in other operating system. For articles on installing pip in Microsoft Windows, read the article with the title of ‘How to Install pip in Microsoft Windows’ in this link. In order to check the ‘pip’ is available or not, just execute it by typing it in the command line as follows :

    C:\Users\Personal>pip --version
    pip 21.0.1 from c:\python38\lib\site-packages\pip (python 3.8)
    
    C:\Users\Personal>
    
    
  3. Following after, check the existance of ‘virtualenv’ library. In order to do that, just run pip list as in the following command :

    C:\>pip list 
    Package Version
    ----------------- ----------
    ...
    virtualenv 20.0.15
    ...
    WARNING: You are using pip version 21.0.1; however, version 21.2.4 is available.
    You should consider upgrading via the 'c:\python38\python.exe -m pip install --upgrade pip' command.
    
    C:\>
  4. Since the ‘virtualenv’ library exist, just execute the following command to create a new python virtual environment folder. As another reference, just look at the article with the title of ‘How to Create a Python Virtual Environment in Microsoft Windows’ in this link.  Just create a python virtual environment as follows :

    C:\programming\python>virtualenv env
    created virtual environment CPython3.8.2.final.0-64 in 13537ms
    creator CPython3Windows(dest=C:\programming\python\env, clear=False, global=False)
    seeder FromAppData(download=False, pip=latest, setuptools=latest, wheel=latest, via=copy, app_data_dir=C:\Users\Personal\AppData\Local\pypa\virtualenv\seed-app-data\v1.0.1)
    activators BashActivator,BatchActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator
    
    C:\programming\python>
  5. Activate the python virtual environment by accessing the folder of the python virtual environment. Following after, execute the following command :

    C:\programming\python>cd env
    
    C:\programming\python\env>cd Scripts
    
    C:\programming\python\env\Scripts>activate
    
    (env) C:\programming\python\env\Scripts>
    

Installing Django Application

After preparing the necessary requirement for installing Django application, just execute the following steps to do it. Those steps exist as follows :

  1. First of all, after activating the python virtual environment, just execute the following command to install module, library or package of Django Application. List the available package first as follows :

    (env) C:\programming\python\env\Scripts>pip list
    Package Version
    ---------- -------
    pip 20.0.2
    setuptools 46.1.3
    wheel 0.34.2
    WARNING: You are using pip version 20.0.2; however, version 21.2.4 is available.
    You should consider upgrading via the 'C:\programming\python\env\Scripts\python.exe -m pip install --upgrade pip' command.
    (env) C:\programming\python\env\Scripts>
  2. Following after, since there is no Django library available, install it by executing the command pip install Django. How about the package name for Django ?. Well, just search it first. Read the article with the title of ‘How to Search Package, Module or Library Python using pip_search’ in this link for searching a package, module or library with the name of ‘Django’ as an example.

  3. After searching it where there is a package with the name of ‘Django’, just install it using ‘pip’ tool. For learning how to do it in detail, just read an article with the title of ‘How to Install Django in Microsoft Windows’ in this link. Another article exist with the title of ‘How to Install Django in Linux via Command Line’ in this link containing similar material. Don’t forget to install another package with the name of ‘django-crispy-forms’.

 

Creating Django Project

After installing the Django application, just continue on to create a new project using the Django framework as folows :

  1. Create a new project by running a certain command.

    (env) C:\programming\python\env\Scripts> cd C:\programming\python
    (env) C:\programming\python>django startproject myproject
    (env) C:\programming\python>cd myproject
    (env) C:\programming\python\myproject>
    

    It exist in an article with the title of ‘How to Create a New Django Project in Linux via Command Line as an example’ in this link.

  2. After that, go to the ‘settings.py’ file inside the ‘myproject’ folder inside the ‘myproject’ folder. Edit it as in the following lines :

  3. INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'crispy_forms',
    ]
    CRISPY_TEMPLATE_PACK = 'bootstrap'
    
  4. Next, just create and edit several files for demonstrating how to present error message in the forms. For the first one, it is editing the file with the name of ‘urls.py’ by adding the following line :

    So, overall for the ‘urls.py’ file, the following is the complete content of it :

    from django.contrib import admin
    from django.urls import path, include, reverse
    from django.views.generic import RedirectView
    from . import views
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('test/', views.TestFormView.as_view(), name='test'),
    ]
    
  5. Next, create a function with the name of TestFormView in the ‘views.py’ as follows :

    class TestCrispyFormView(FormView):
        form_class = TestCrispyForm
        template_name = 'templates/test-crispy.html'
    

    The content of the views.py for accomodating the TestCrispyFormView class as exist in the above definition for a complete display exist as follows :

    from django.views.generic import FormView, TemplateView
    from django.shortcuts import render
    from django.urls import reverse_lazy, reverse
    from django.http import HttpResponseRedirect
    from .forms import ContactForm, AddressForm, TestForm, TestCrispyForm
    class TestCrispyFormView(FormView):
        form_class = TestCrispyForm
        template_name = 'templates/test-crispy.html'
    # class ListFormView(request):
    #    return render(request, 'templates/list.html')
    
  6. Next, creates a class with the name of TestCrispyForm in the forms.py file as follows :

    class TestForm(forms.Form):
        first_name = forms.CharField(widget=forms.TextInput(
            attrs={'placeholder': 'First Name'}))
    
  7. Overall, the content of the forms.py file for a complete content exist as follows :

    from django import forms
    from django.urls import reverse, reverse_lazy
    from django.shortcuts import redirect
    class TestCrispyForm(forms.Form):
        first_name = forms.CharField(widget=forms.TextInput(
            attrs={'placeholder': 'First Name'}))
    
  8. Last but not least, the following is the content of the HTML template file as follows :

    {% extends 'base.html' %} {% block content %}
    <form action="{% url 'test' %}" method="POST">
      {% csrf_token %}
      <div class="form-group">
        <label for="exampleInputName">Name</label>
        <input
          type="text"
          class="form-control"
          name="first_name"
          aria-describedby="name"
          placeholder="Name"
        />
      </div>
      {% if form.errors %} 
            {% for field in form %} 
               {% for error in field.errors %}
                  <div class="alert alert-danger">
                       <strong>{{ error|escape }}
                       </strong>
                  </div>
               {% endfor %} 
           {% endfor %} 
      {% endif %}
      <button type="submit" class="btn btn-primary">Submit</button>
    </form>
    {% endblock %}
    

    As in the above definition, there is part which is showing how to handle the form error. It is in the following part :

    {% if form.errors %} 
            {% for field in form %} 
               {% for error in field.errors %}
                  <div class="alert alert-danger">
                       <strong>{{ error|escape }}
                       </strong>
                  </div>
               {% endfor %} 
           {% endfor %} 
      {% endif %}
    

    The following is a display of image containing error message when the text field for name is empty on clicking the submit button :

Leave a Reply