Recently, I got one requirement to create a contact form in Django and save the data to a database. And here, I will explain step by step how to build a contact form in Django using bootstrap.
I’m currently working on a Django project for a project builder website where a bootstrap contact form is required, so I have done some research and decided to write an article on it.
Here we will see:
- How to build a contact form in Django using bootstrap
- How to use various controls like textbox, textarea, dropdown, datepicker in Django
- Save contact form data to SQLite database
- How to view submitted data from the Django admin interface
There are different ways, we can create contact forms in Django like using forms, crispy forms, HTML, etc. But we will focus on creating a contact form in Django using bootstrap.
At the end of this article, you can also download the code: build a contact form in Django using bootstrap.
This is what we will build here.
Contact form in Django using bootstrap
Now, let us see, step by step how to build a contact form in Django using bootstrap.
Set up project
A project is a Django-based web application. There is always only one project with a variety of apps inside of it. Therefore, we need to establish a project and an app for our contact form first.
Firstly, create a project in Django named ProjectGuides using the below-given command.
django-admin startproject ProjectGuides
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.
Django by default includes a urls.py file in the project directory. It maps the newly constructed app Contact inside of it.
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('Contact.urls')),
]
Create model in Django
Django models are tables in your database that are used to store project data.
To create models in Django 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_budget = (
("1", "45000"),
("2", "30000"),
("3", "20000"),
("4", "15000"),
("5", "10000"),
)
class Contact(models.Model):
name = models.CharField(max_length=250)
organization = models.CharField(max_length=400),
email = models.EmailField()
description = models.TextField(max_length=1200)
budget = models.IntegerField(choices=select_budget,default='3')
date = models.DateField()
def __str__(self):
return self.email
Here, we create a model class Contact which has the following fields.
- The name is Django CharFields to take name input from the user. And there is a 250-character limit for this character field.
- The organization is Django CharFields to take organization name input from the user. And there is a 400-character limit for this character field.
- The email is Django EmailField which allows users to save email addresses.
- The description field is Django TextField. And there is a 1200-character limit for it.
- The budget is Django IntegerField. 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_budget.
- The date is Django DateField to take date input from the user.
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)
Create Templates
Our main objective is to build a contact form in Django using bootstrap. In Django HTML, CSS, Javascript, and Bootstrap should be created in a template, so let’s do that.
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 then update the DIRS to refer to the Templates folder’s location.
To create a contact form in Django using bootstrap we need to create an HTML file. This file defines the contact form fields, so 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 Us</title> <style> .vl { border-left: 4px solid green; height: 600px; } </style> </head> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> </head> <body> <div class="mt-md-5"> <div class="container"> <div class="row"> <div class="col-sm"> <h3 align="center">Welcome to PythonGuides</h3> <br> <hr> <p> PythonGuides is Website Builder who offers 5000+ website blocks that includes articles, online shops, gallaeries, articles, blog posts, chat buttons, google maps, social feeds, etc. The newest web design trends are taken into account when creating blocks, which are adaptable and loaded with customization choices. </p> <br> <br> <p> PythonGuides is best for non-techies who are not familiar with the complexities of web design and prefer to join a non-code revolution. And also benifical for pro-devs and web agencies for fast prototyping and small customer's projects. </p> <br><br> <p> PythonGuides is premium website to easily build small/large websites, templates, themes and pages.</p> </div> <div class="vl"> </div> <div class="col-sm"> <h3 align="center">HOW CAN WE HELP?</h3> <br> <hr> <br> <form method="POST" class="post-form" enctype="multipart/form-data"> {% csrf_token %} <div class="form-row"> <div class="form-group col-md-6"> <label for="name">Name:</label> <input type="text" class="form-control" id="name" name="name" placeholder=" Your Name"> </div> <div class="form-group col-md-6"> <label for="organization">Organization:</label> <input type="text" class="form-control" id="organization" name="organization" placeholder="Your Organization"> </div> </div> <div class="form-group"> <label for="email">Email:</label> <input type="email" class="form-control" id="email" name="email" placeholder="Your Email Address"> </div> <div class="form-group"> <label for="description">Project Description:</label> <textarea class="form-control" id="description" name="description" rows="3"></textarea> </div> <div class="form-row"> <div class="form-group col-md-6"> <label for="budget">Budget:</label> <select id="budget" name='budget' class="form-control"> <option selected>Choose</option> <option value="1">45000</option> <option value="2">30000</option> <option value="3">20000</option> <option value="4">15000</option> <option value="5">10000</option> </select> </div> <div id="date" class="md-form md-outline input-with-post-icon datepicker" inline="true"> <label for="date">Delivery Date:</label> <input placeholder="Select date" type="date" id="date" name="date" class="form-control"> </div> </div> <button type="submit" class="btn btn-success">Submit</button> </form> </div> </div> </div> </div> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> </body> </html>
First, load your CSS by adding the stylesheet’s link to your page’s header before any other stylesheets. Then, to add bootstrap padding use the div class mt-md-5.
After that, to provide a responsive fixed-width container, use the div class container, and inside it create two equal-width columns on small devices within the single row using the div class row and div class col-sm class.
To describe about our website on the left-hand side of the contact form we use the h3, br, hr, and p tags inside the first column.
Now, we utilize the div class v1, in the style element inside the title tag, to draw a vertical line between the two columns.
To build the contact form using bootstrap we use the h3, br, hr, and form tags inside the second column.
And the following are the contact form fields that we define using the bootstrap div class form-group.
- We use the input type=”text”, which defines a single-line text, for the name and organization field.
- We utilize the input type=”email” tag to define an email address in the email field.
- The textarea element is used in a form, to collect user input description.
- The select name attribute specifies the budget for a drop-down list.
- The input type=”date” is utilized to define the date field for entering a date.
- Lastly, add a submit button to submit the form.
The functionality of several of our components depends on JavaScript. For this, they specifically need our JavaScript plugins, Popper.js, and jQuery and to enable the following scripts, we add them just before the closing body tag.
On the successful submission of the contact form, we want to render it to some other page, so we get the success message and the contact form link again. For this, we create one more HTML file named success.html inside 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>
Here, the h2 tag is used to create the heading and to align text in the center, and set its color to red we use the text-align and color attribute. Then to connect it back to the contact form, we use the a href tag within the p tag.
Read: Run Python function by clicking on HTML Button in Django
Define View
Django view is a Python function where we put the business logic of the application and return a response to the user.
To create the main logic for the creation of the contact form using bootstrap, 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['name']
organization = request.POST['organization']
email = request.POST['email']
description = request.POST['description']
budget = request.POST['budget']
date = request.POST['date']
data = Contact(name=name,organization=organization, email=email, description=description, budget=budget, date=date)
data.save()
return render(request, 'success.html')
else:
return render(request,'contact.html')
First import the Contact from the models.py, then call the if statement and check whether the request method is POST.
If yes, we fetch the name, organization, email, description, budget, and date using the request.POST[‘field-name’] method. Then, the Contact() method receives all the fields as input and initializes it to a data variable. Then we save the data to the model using the save() method and render the user to the success.html.
If no, the user gets an empty contact form which displays through contact.html in the render() function.
To call the view, we have to map it with the URL, so we have to create a urls.py file under the app directory. Add the below code in it.
from django.urls import path
from Contact import views
urlpatterns = [
path("contact", views.contact, name="contact"),
]
Read: Python Django get admin password
Execute Django Application
As we are working with the model we first need to generate a migration for the specified model. Run the following command in the terminal.
python manage.py makemigartions
To reflect the database, we need to migrate it. The migrate command is given below.
python manage.py migrate
To start up a development server for this specific Django project, we run the below command in the terminal.
python manage.py runserver
To open the contact form, expand the URL as shown below.
127.1.1.0/contact
It successfully opens the Django contact form that we create using bootstrap which looks like this.
Now, fill out this contact form and click on the Submit button as follows.
After clicking on submit, it will move to the success page. If we click on the Contact Page link, we will again redirect to a blank contact form.
Read: Python Change Django Version
View submitted data from the Django admin interface
Django provides an admin panel for its users and we can view the data we saved from the form to the database through it. Firstly, we have to create a superuser for it by the below-given command.
python manage.py createsuperuser
Click on contacts under the CONTACT app. And we will get the data saved on the database. Here, is the sample.
This is how you create a contact form in Django using bootstrap4.
Read: Python Django set timezone
Download Contact form in Django using bootstrap complete code
Here is the code:
Conclusion
With this, we have successfully created a working contact form using bootstrap in the Django project. We have also learned to make use of a database, save data from the contact form and view the data in the admin panel.
Additionally, we have also covered the following topic.
- How to build a contact form in Django using bootstrap
- How to use various controls like textbox, textarea, dropdown, datepicker in Django
- Save contact form data to SQLite database
- How to view submitted data from the Django admin interface
You may also like to read the following Python Django tutorials.
- Python Django form validation
- How to Create model in Django
- Python Django app upload files
- Python Django MySQL CRUD
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.