Simple Contact Form for website in Python Django

In this Python Django tutorial, I will explain how to build simple contact form for website in Python Django step by step.

Recently, I have been creating a website for PythonGuides using the Django framework. And I have found that it requires a contact form for communication with the website workers.

So, I have done some research and created a contact form for a website in Django using FormClass which looks as follows.

python django contact form
Simple Contact Form for Website in Python Django

Here we will see:

  • What is contact form
  • How to set up a simple contact form for website in Python Django
  • How to add max_length form validation in Django
  • How to render the form as a paragraph in Django
  • How to view form data on the Django terminal

At the end of this article, you can also download the code: Create a simple contact form for website in Python Django.

How to create a simple Contact form for website in Python Django

Now, let us see, step by step how to build a Contact Form for a Python Django Application.

Contact Form

We have probably noticed that on most company websites, there is a page on a website that allows visitors to communicate with the site owner.

Name, address, and type of comment are frequently required fields on the page, and occasionally an email address is as well. This page is known as a contact page and consists contact form.

In simple words, the contact form provides a quick and easy way to users to ask the company their queries.

How to set up a simple contact form for website in Python Django

To start a Django project, open the terminal and enter the following command. Here PythonGuides is the name of the Django Project.

django-admin startproject PythonGuides

It will make a new folder called PythonGuides and to enter in the project type the below command in the terminal.

cd PythonGuides

Now, create a Django app named Contact inside this project folder, by typing the below command in the terminal.

python manage.py startapp Contact

To activate this app, add the app name to the INSTALLED_APP list located in the settings.py file.

python django contact form
Settings.py

Django by default includes a urls.py file in the project directory to map the newly constructed app inside of it. 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 form validation

Create Simple Form

Create the Django form that takes input from the users for the Contact application. For this, create the forms.py file inside the app directory and add the below-given code.

from django import forms

# Create your forms here.

class ContactForm(forms.Form):
	first_name = forms.CharField(max_length = 100)
	last_name = forms.CharField(max_length = 100)
	comment = forms.CharField(widget = forms.Textarea, max_length = 1500)

Here, we create a form class ContactForm which has the following fields.

  1. The first_name and last_name as Django CharFields. And there is a 100 max_length character limit for each of these character fields.
  2. The comment field as Django CharField with a widget specifying the form will display as a Textarea. And there is a 1500 max_length character limit for it.\

Read: Run Python function by clicking on HTML Button in Django

Render the form as a paragraph in Django

In Django, the front end of the application is defined in Templates, so for this, create a subdirectory called Templates in the main project directory to store all of the project templates.

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

django contact form example
Setting Templates Folder Location

To define the front end of the contact webpage creates an HTML file named contact.html inside the Templates folder. And add the below-given code.

<div style="margin:80px">
    <h1 align="center">Contact Form</h1>
    <hr>
    <h4>Contact us directly if you have any queries</h4>
    <hr>
    <br>
    <form method="post">
        {% csrf_token %}
        {{form.as_p}}
        <button type="submit">Submit</button>
    </form>
</div>
  • 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 you to send the information securely, add the {% csrf_token %} within the form element.
  • Next, to render the form as a paragraph use the form.as_p tag.
  • Lastly, add a submit button to submit the form.

View form data on the Django terminal

To define the main logic for the simple contact form, we open the views.py file and add the below-given code.

from django.shortcuts import render
from .forms import ContactForm

# Create your views here.

def contact(request):
	if request.method == 'POST':
		form = ContactForm(request.POST)
		if form.is_valid():
			first_name = form.cleaned_data['first_name']
			last_name = form.cleaned_data['last_name']
			comment = form.cleaned_data['comment']
			print('First Name:', first_name)
			print('Last Name:', last_name)
			print('Comment:',comment)	      
	form = ContactForm()
	return render(request, "contact.html", {'form':form})
  • First import the ContactForm from the forms.py, then call the if statement and check whether the request method is POST.
  • If yes, we pass ContactForm(request.POST) that binds the data to the form class, so we can do validation.
  • Now, call the is_valid() to validate the input entered by the user, and if validation success calls the form.cleaned_data[‘form_field’] that cleans the data and prints it on the terminal using the print() function.
  • If the request method is GET, the user is presented with a blank contact form using the render() function.

Now, 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. Include the code below in it.

from django.urls import path
from Contact import views

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

Read: How to Create model in Django

Execute Contact Form Django Application

The manage.py file for Django includes a built-in subcommand called runserver that will begin a development server for the particular Django project.

Type the below-given command in the terminal and run the server.

python manage.py runserver

Every Internet page requires a unique URL. By doing this, your application will be able to identify what to display when a user opens that URL.

By default, Django localhost displays the URL as 127.0.0.1:8000/. Now extend this URL as follows to open the contact form.

127.0.0.1:8000/contact

It successfully opens the Django simple contact form which looks like this.

python django contact form
Contact Us

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

djnago contact form
Simple Contact Form for the website

After clicking on submit, it will print First Name, Last Name, and Comment on the terminal.

contact form using django python
Output on the terminal after submission of the Contact Form

This is how we can build a simple Django contact form for a Django website.

Read: Python Django app upload files

Download the Django build a simple contact from complete code

Here is the code.

Conclusion

With this, we have successfully built a simple contact form using the Form Class in the Django project. We have also learned to render the form as a paragraph and view the form data in the terminal.

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

Additionally, we have also covered the following topic.

  • What is contact form
  • How to set up a simple contact form for website in Python Django
  • How to add max_length form validation in Django
  • How to render the form as a paragraph in Django
  • How to view form data on the Django terminal