Django contact form with class based views

In this Python Django tutorial, I will explain how to create a Django contact form with class-based views.

While working on a contact form, I just learned that creating a contact form using function-based views takes dozens of lines of code and a lot of work and time.

So, after doing some research, I learned that Django has class-based views. Here, we’ll concentrate on the handling Django contact form with class based views.

Here we will see:

  • Build a Django contact form with class based views
  • Form handling with class-based FormView in Django
  • How to use TemplateView in Django
  • How to use various controls like textbox, email, and character filed in Django
  • How to render the form as a table in Django

At the end of this article, you can also download the code: Contact form with class-based views.

This is what we will build here.

django contact form with class based views
Django Contact Form with class based views

Build a Django contact form with class based views

Now, let us see, step by step how to handle Django form with class-based FormView.

Setup Django Project

Firstly, create a project in Django named Tutors using the below-given command.

django-admin startproject Tutors

Create a Django app named Contact, within the Django project, by typing the below command in the terminal.

python manage.py startapp Contact

Add the Contact app to the installed app list located in the settings.py file.

create a django contact form with class based views
settings.py

Django by default includes a urls.py file in the project directory to map the newly constructed app inside of it. To do this add the below code in it.

from django.contrib import admin
from django.urls import path,include

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

Django Form with various fields

Create the Django form that the Contact application will use to collect user input.

Create the forms.py file in the app directory and add the following code there to do this.

from django import forms

# Create your forms here.

class TutorBookForm(forms.Form):
    name = forms.CharField(max_length=50)
    email = forms.EmailField()
    message = forms.CharField(widget=forms.Textarea)

Here, we create a form class called TutorBookForm with the fields listed below.

  • The name field is Django CharField. Additionally, this character field has a 50 max_length character restriction.
  • The email field is Django EmailField. This field is used to collect emails from the user.
  • The message field is Django CharField with a widget specifying the form will display as a Textarea. 

Read: Python Change Django Version

Render the form as a table in Django

To allow developers to embed Django logic codes into HTML template files, Django Template was created.

For this, create a subdirectory called Templates in the main project directory to store all of the project templates.

Then, open the settings.py file, and update the DIRS to refer to the Templates folder’s location.

django form handling with class based form views
settings.py

Create a file called form.html in the Templates folder to define the contact webpage’s front end. Add the code that is given 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>Contact Us</title>
</head>

<body>
    <h1 align="center">Connecting With Us</h1>
    <hr>
    <form method="post">
        {% csrf_token %}
        <table>
        {{form.as_table}}
        </table>
        <button type="submit">Send Message</button>
    </form>
</body>

</html>
  • Firstly add the heading to the form using the HTML tag h1 and also add a horizontal line using the hr tag.
  • Then call the form tag with the method POST, so the form is posted upon submission.
  • To prevent the form from cyber attacks and allow you to send the information securely, add the {% csrf_token %} within the form element.
  • Next, to render the form as a table use the form.as_table tag within the table tag.
  • Lastly, add a submit button to send the message.

When the contact form is successfully submitted, we want to render it to another page, so we receive the success message and the contact form link once again.

To do this, we add another HTML file called success.html to the Template Folder.

<!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>Success Page</title>
</head>

<body>
    <h2 style="text-align: center; color: red;" "></h2style>Your form is successfully submitted.</h2>
    <p> You can send another in the <a href=" {% url 'contact' %}">Contact Page</a></p>
</body>

</html>

The h2 tag is used to define the heading, and the text-align and color attributes are passed inside the tag to center the text and set its color to red. The contact page is then linked to inside the p tag using the a href tag.

Read: Python Django form validation

Logic to handle Django contact form with class-based FormView

To define the main logic for the creation of the contact form using the class-based views, we open the views.py file and add the below-given code.

from django.shortcuts import render
from .forms import TutorBookForm
from django.views.generic.edit import FormView
from django.views.generic.base import TemplateView

# Create your views here.

class TutorBookFormView(FormView):
    template_name = 'form.html'
    form_class = TutorBookForm
    success_url = '/success/'

class SuccessView(TemplateView):
    template_name = 'success.html'
  • First, import the ContactForm from the forms.py.
  • Then, import FromView class and TemplateView class from the generic.edit and generic.base module respectively.
  • Next, create a subclass named TutorBookFormView, then extend it with an existing view named FormView.
    • Inside this class-based view, we override the template_name, form_class, and success_url attributes on it, which respectively take the template as form.html, form as TutorBookForm, and redirect to the success view when we submit the form successfully.
  • Then, we create a subclass named SuccessView and extend it with an existing view named TemplateView.
    • Inside this class-based view, we override the template_name attributes on it, which respectively take the user to the template named success.html.

We must map the view with the URL in order to call it, thus we must create a file called urls.py in the app directory. And include the code below in it.

from django.urls import path
from .views import TutorBookFormView,SuccessView

urlpatterns = [ 
    path("contact", TutorBookFormView.as_view(), name="contact"),
    path("success/", SuccessView.as_view(), name="success"),  
]

Read: Python Django MySQL CRUD

Execute Django Application

To start a development server for this particular Django project, we enter the command below into the terminal.

python manage.py runserver

We access the contact form by expanding the URL, as it is shown below.

127.1.1.0/contact

It successfully opens the Django contact form that we create using the class-based views which looks like this.

django contact form with class based views
Contact Us

Now, fill out the contact form and click the Send Message button as shown below.

handle python django contact form with class based views
Contact Form with class-based view

Once we click submit, we’ll be taken to the success page. If we hit the Contact Page link, we will again be taken to a contact form that is unfilled.

python django contact form with class based views
Success Page

Also, check: Django CRUD example with PostgreSQL

Download the Django Contact form with class based views complete code.

Here is the code.

Conclusion

With this, we have successfully created a working Django contact form with class based views. We have also learned how to use FormView class and TemplateView class in Python Django.

Additionally, we have also covered the following topics.

  • Build a Django contact form with class based views
  • Form handling with class-based FormView
  • How to use TemplateView in Django
  • How to use various controls like textbox, email, and character filed in Django
  • How to render the form as a table in Django

Also, take a look at the following Python Django tutorials.