How to create Contact Form with Django and SQLite

Recently, I got one requirement to create a contact form in Django and save the data to an SQLite database. And here, I will explain step by step how to create Contact Form with Django and SQLite.

As a Python Django Developer, I got a requirement of creating a website for a Training Course and in it, I required a contact form with SQLite databases.

Here we will see:

  • How to Save Data from HTML Form to Database
  • How to use various controls like textbox, textarea, email, and radio buttons in Django
  • How to remove required form validation in Django
  • How to add custom validation on a phone number
  • How to the build contact form using HTML in Django
  • How to view submitted data from the Django admin interface

There are different ways, we can create contact forms in Django like using Form, ModelForm classes, and HTML. But we will focus on creating a contact form in Django using HTML.

At the end of this article, you can also download the code: Contact Form with Django and SQLite.

This is what we will build here.

djnago contact form with database
Contact Form with Django and SQLite

Contact Form with Django and SQLite

Now, let us see, step by step how to Save Data from HTML Form to Database.

Firstly, we need to establish a project in Django using the below-given command. Here TrainingGuides is the name of the project.

django-admin startproject TrainingGuides

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_APPS list located in the settings.py file.

contact form using django
settings.py

A request in Django first comes to urls.py located inside the project directory and then goes to the matching URLs in urls.py inside the app directory. 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')),
]

Read: Python Django get admin password

Create Model using Django

To store project data create Django models that are basically tables in our database. For this, open the models.py file inside the app directory and add the below-given code.

from django.db import models

# Create your models here.

select_mode_of_contact = (
    ("email", "E-Mail"),
    ("phone", "Phone"),
)
select_question_categories = (
    ("certification", "Certification"),
    ("interview", "Interview"),
    ("material", "Material"),
    ("access_duration","Access and Duration"),
    ("other", "Others"),
)

class Contact(models.Model):
    name = models.CharField(max_length=250)
    email = models.EmailField()
    phone = models.CharField(max_length=10)
    mode_of_contact = models.CharField('Conatct by', max_length=50,choices=select_mode_of_contact,default='email')
    question_categories = models.CharField('How can we help you?', max_length=50,choices=select_question_categories,default='certification')
    message = models.TextField(max_length=3000)

    def __str__(self):
        return self.email

Here, we create a model class Contact which has the following fields.

  1. The name is Django CharFields. And there is a 25-character limit for this character field.
  2. The email is Django EmailField which allows users to save email addresses.
  3. The phone is Django CharField. And there is a 10-character limit for this character field.
  4. The mode_of_contact and question_categories are Django CharField. And there is a 50-character limit for these character fields. Additionally, there is a choices option that are sequences that may be used as options for a field and consists of iterables for items and we define a tuple for this named select_mode_of_contact and select_question_categories.
  5. The message field is Django TextField. And there is a 3000-character limit for it.
READ:  How to use TensorFlow get_shape Function (get tensor shape)

And to change the display name of the object in the Django model use the def __str__(self). It will render the item name as email as we return the self.email.

Register the Contact model to the admin site so that the user can view it in the admin application. Open the admin.py file and add the below-given code.

from django.contrib import admin
from .models import Contact

# Register your models here.

admin.site.register(Contact)

Read: Python Django vs Pyramid

Define Django Form with validation

Our main objective is to build a contact form in Django using HTML. So, create a subdirectory called Templates in the main project directory to store all of the project templates.

After that, open the settings.py file to configure the Django template system and update the DIRS to refer to the Templates folder’s location.

python django contact form from database
settings.py

To create a contact form in Django using HTML we need to create an HTML file. To define the contact form fields, we create contact.html in the Templates folder and include the code 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</title>
</head>

<body>
    <div style="margin:80px">
        <h1 align="center">Contact Us</h1>
        <hr>
        <h4>Contact us directly if you have any queries. We will get in touch with you shortly.</h4>
        <hr>
        <br>
        <form method="post">
            {% csrf_token %}
            <table>
                <tr>
                    <th>
                        <label for="name">Name:</label>
                    </th>
                    <td>
                        <input type="text" id="name" name="name" required>
                    </td>
                </tr>
                <tr>
                    <th>
                        <label for="email">E-mail:</label>
                    </th>
                    <td>
                        <input type="email" id="email" name="email" required>
                    </td>
                </tr>
                <tr>
                    <th>
                        <label for="phone">Phone:</label>
                    </th>
                    <td>
                        <input type="tel" id="phone" name="phone" pattern="[0-9]{3}-[0-9]{2}-[0-9]{3}">
                    </td>
                </tr>
                <tr>
                    <th>
                        Contact me by:
                    </th>
                    <td>
                        <label for="email">E-Mail</label>
                        <input type="radio" id="email" name=contact value="email">

                        <label for="phone">Phone</label>
                        <input type="radio" id="phone" name=contact value="phone">
                    </td>
                </tr>
                <tr>
                    <th>
                        <label for="queries">How can we help you?:</label>
                    </th>
                    <td>
                        <select name="queries" id="queries">
                            <option value="certification">Certification</option>
                            <option value="interview">Interview</option>
                            <option value="material">Material</option>
                            <option value="access_duration">Access and Duration</option>
                            <option value="other">Others</option>
                        </select>
                    </td>
                </tr>
                <tr>
                    <th>
                        <label for="message">Message:</label>
                    </th>
                    <td>
                        <textarea id="message" name="message" rows=10 cols=40 maxlength=3000 required></textarea>
                    </td>
                </tr>
            </table>
            <button type="submit">Submit</button>
        </form>
</body>

</html>
  • Firstly add the heading to the form using the HTML tags h1 and h4.
  • 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 us to send the information securely, add the csrf_token within the form element.
  • Then, call the table tag to create an HTML table, and within this call tr tag to define table rows.
  • Next, within each table row, we call th tag that defines a table header as Name, E-mail, Phone, Contact me by, How can we help you? and message.
  • Then to define these headers we call the td tag.
  • And the following are the fields that we define inside the td tag.
    • We use input type=”text”, which defines a single-line text, for the name field.
    • We utilize the input type=”email” tag to define an email address in the email field.
    • The input type=”tel” is utilized to define the phone field for entering a telephone number. We also added custom validation on this field.
    • The input type=”radio” is utilized to define the mode_of_contact field as a radio button. Radio buttons are used to describe a set of related options and one can be selected at a time.
    • The select name= attribute specifies the question_categories for a drop-down list.
    • The textarea element is used in a form, to collect user input message.
  • We also set the required field validation, on the name, email, and message fields by passing the required attribute to the input tag.
  • Lastly, add a Submit button to submit the form.
READ:  Module 'tensorflow' has no attribute 'sparse_placeholder'

We want to render the contact form to another page when it is successfully submitted, so we receive the success message and the contact form link once more. To accomplish 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>Document</title>
</head>

<body>
    <h2 style="text-align: center; color: red;" "></h2style>We sent your message</h2>
    <p> You can send another in the <a href=" {% url 'contact' %}">Contact Page</a></p>
</body>

</html>

The h2 tag is used to create the heading, and the text-align and color attributes are used to center the text, align it, and change its color to red. Then, within the p tag, we use the a href tag to link it to the contact form.

Read: Python Change Django Version

Define Django View

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

from django.shortcuts import render
from .models import Contact

# Create your views here.

def contact(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        email = request.POST.get('email')
        phone = request.POST.get('phone')
        mode_of_contact = request.POST.get('contact')
        question_categories = request.POST.get('queries')
        message = request.POST.get('message')
        contact_data = Contact(name=name, email=email, phone=phone, mode_of_contact=mode_of_contact, question_categories=question_categories, message=message)
        contact_data.save()
        return render(request, 'success.html')
    return render(request, 'contact.html')
  • Import the Contact model defined in the models.py file.
  • Then call the if statement and check whether the request method is POST.
    • If yes, fetch all the fields defined in the form using the request.POST.get(‘html-field-name)
    • Now, pass it to the constructor of the model and save the data using the save(), and render the user to the success.html.
  • If the request method is GET, the user is presented with a blank contact form using the render() function.
READ:  Write a Python Program to Check Whether a List Contains a Sublist

To call the view, we must associate it with the URL, thus we must create a file called urls.py in the app directory. Include the following code in it.

from django.urls import path
from Contact import views

urlpatterns = [
    path("contact", views.contact, name="contact"),   
]

Read: Python Django vs ReactJS

Execute Django Application

The first thing you must do after creating the model is to create a migration for it. You can execute this with the command.

python manage.py makemigrations

Having now created the migration, you must use the migrate command to actually apply any changes to the database.

python manage.py migrate

To start up a development server for this specific Django project,  we can run a special command at the terminal.

python manage.py runserver

By expanding the URL as shown below, we can access the contact form.

127.1.1.0/contact

It successfully opens the contact form created using HTML and SQLite, which has the following look.

django contact form with database
Contact Form using HTML

Now, fill out this contact form and click on the Submit button as follows.

python django contact form with database
HTML Contact Form

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.

contact form with database using django
Success Page

Read: Python Django MySQL CRUD

View submitted data from the Django admin interface

It will also save the data in the database. So, create a superuser and open the admin application and view it.

conatct form with database using python django
Save Data from HTML Form to Database

This is how you create a Contact Form with Django and SQLite.

Download Django Contact Form with Django and SQLite complete code

Here is the code:

Conclusion

With this, we have successfully created a Contact Form that Save Data from HTML Form having various controls like textbox, textarea, email, and radio buttons to the Database. We have also learned to remove the required validation and view the submitted form data on the admin interface.

Additionally, we have also covered the following topics.

  • How to Save Data from HTML Form to Database
  • How to use various controls like textbox, textarea, email, and radio buttons in Django
  • How to remove required form validation in Django
  • How to add custom validation on a phone number
  • How to the build contact form using HTML in Django
  • How to view submitted data from the Django admin interface

You may also like to read the following Python Django tutorials.