Django Contact Form

On January 07, 2024
6min read
Denys Kontorskyy Technical Content Writer @Mailtrap

You’re in luck if you’re building a website using the powerful Python web framework Django. In addition to being great for rapid and secure web development, the framework provides an easy way to create and customize a contact form.

Whether you’re a beginner or a Jedi developer who needs a refresher, this tutorial provides a solid foundation for building a robust and effective contact form that can be featured on your homepage.

How to create a Django contact form?

Before diving into the steps, you need to take to build the form, let’s review the basic requirements.

First and foremost, make sure that Django is installed on your machine. From the command prompt, run this command:

pip install django

If you have a particular version that you need and not the latest one that is installed by default, run this command and indicate the version number:

pip install django==4.2

Next, you’ll need to set up an actual project before beginning with the contact form. Do this by running the command django-admin startproject <projectname>, where <projectname> is the name you want to give to your Django project. In our example, we’ll name it myproject

django-admin startproject myproject

This command creates a new directory called myproject that contains the main settings and configuration files.

myproject/
    manage.py
    myproject/
        __init__.py
        settings.py
        urls.py
        asgi.py
        wsgi.py

***The manage.py file is a command-line utility that helps to interact with the project.

Now you’re ready to start building the basic contact form.
Start by creating a new forms.py file in myproject folder.

To access various form-related functionalities, such as validation and rendering, create a form class that inherits Django’s built-in Form class. This is where you can define the form fields you want to collect from the user. Here’s the full code that will go in the file:

from django import forms


class ContactForm(forms.Form):
    name = forms.CharField(required=True)
    email = forms.EmailField(required=True)
    message = forms.CharField(widget=forms.Textarea)

This is just a basic example, but you can add additional fields and built-in validations to ensure that the user inputs correct data:

from django import forms
from django.core.validators import EmailValidator


class ContactForm(forms.Form):
    name = forms.CharField(max_length=100)
    email = forms.CharField(validators=[EmailValidator()])
    phone = forms.CharField(max_length=15)
    subject = forms.CharField(max_length=100)
    message = forms.CharField(widget=forms.Textarea)

Once the contact form class is created, create a new views.py file, and in it, add a view function that’ll render the contact form template and handle the submission:

from django.shortcuts import render, redirect
from myproject.forms import ContactForm
from django.http import HttpResponse


def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            # Process the form data
            pass
            return redirect('success')
    else:
        form = ContactForm()
    return render(request, 'contact.html', {'form': form})


def success(request):
   return HttpResponse('Success!')

Here, we have defined a view function called contact that takes a web request and returns a rendered contact form template.

  • The view function is responsible for:
    • processing the form data submitted by the user
    • checking if the request is a POST request 
    • Creating an instance of the ContactForm class to validate the submitted data via is_valid() method

In this example, we simply pass, but you can also:

  1. Send form data via email. We’ll cover this in more detail with code examples in the next step below. 
  1. Save form data to a database:
import csv
from django.shortcuts import redirect

name = form.cleaned_data['name']
email = form.cleaned_data['email']
message = form.cleaned_data['message']

file = open('responses.csv', 'a')
writer = csv.writer(file)
writer.writerow([name,email,message])
file.close()

return redirect('success')

Note that this approach saves the form data to a CSV file instead of a database. To save form data to a database, you’ll need to define a model to store the data. For more information on defining models in Django, check out the Django tutorial on setting up models.

To use the view function we created, you’ll also need to map a URL to the view function to create a webpage or endpoint accessible via the URL.

This is done using the path() function that defines a URL pattern that points to the contact() function. Note that this code should go to the file called myproject/urls.py

from django.urls import path
from myproject.views import contact, success

urlpatterns = [
    path('contact/', contact, name='contact'),
    path('success/', success, name='success')
]

At this point, you’ll need to write the HTML for the contact form from scratch or use a ready-made template file. There are several sources for HTML templates, and the one you choose depends on the specific design and functionality you need.

Here are some simple steps you can take to set up a template that works with our guide:

  • Add this to TEMPLATES setting in settings.py:
'DIRS': [
           os.path.join(BASE_DIR, "templates")
       ],
  • Create templates/contact.html in our project with the following contents
<form action="/contact/" method="post">
   {% csrf_token %}
   {% for field in form %}
       <div class="fieldWrapper">
           {{ field.errors }}
           {{ field.label_tag }} {{ field }}
       </div>
   {% endfor %}
   <input type="submit" value="Submit">
</form>
  • As a last touch, add a success page to which the user is redirected to after hitting the submit button: 
from django.shortcuts import render, redirect
from myproject.forms import ContactForm

def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            # Process the form data
            return redirect('success')
    else:
        form = ContactForm()
    return render(request, 'contact.html', {'form': form})

def success(request):
    return render(request, 'success.html')

To run all of the example codes from this tutorial, and to check the result, execute the following command in your terminal: python3 manage.py runserver

After that, open your web browser and enter this URL http://127.0.0.1:8000/contact/

to access the contact form page.  Here’s an example of what you should see: 

How to send an email via a Django contact form?

As shown earlier, there are a few actions that you can set the form to do once it’s submitted. In most cases, you’ll want it to send an email with the form’s information. For this to happen, you’ll need to list the SMTP server configuration and your credentials in the settings.py file.

In the following code example, we are using Mailtrap Email Sending as the SMTP server, but of course, it can be Gmail or any other SMTP server of an email service provider.

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'live.smtp.mailtrap.io'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'example_username'
EMAIL_HOST_PASSWORD = 'example_password'
EMAIL_USE_TLS = True

Once you’ve configured your email settings, use Django’s built-in email sending functionality to send an email in your view function.

Here’s a full code of how to modify the contact() view function we created earlier to send an email:

from django.shortcuts import render, redirect
from django.core.mail import EmailMessage
from myproject.forms import ContactForm
from django.conf import settings

def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            email = form.cleaned_data['email']
            message = form.cleaned_data['message']


           EmailMessage(
               'Contact Form Submission from {}'.format(name),
               message,
               'form-response@example.com', # Send from (your website)
               ['JohnDoe@gmail.com'], # Send to (your admin email)
               [],
               reply_to=[email] # Email from the form to get back to
           ).send()

            return redirect('success')
    else:
        form = ContactForm()
    return render(request, 'contact.html', {'form': form})

Testing your contact form with Mailtrap Email Testing

For proper functionality, testing your contact form, and for that matter, any email sent by your Django application or website before deployment, is always recommended.

Email Testing by Mailtrap Email Delivery Platform is a useful tool for testing email functionality in a development environment without the risk of spamming users.

By intercepting and capturing all emails sent by your Django app, Email Testing lets you evaluate the compatibility of your email’s HTML/CSS with different email clients, check how emails will appear on various devices, get a detailed spam analysis, and review raw email data.

Additional Email Testing checks and lets you know if your email address appears in any critical email blacklists. 

Once you have a Mailtrap account, configure Email Testing SMTP credentials in the settings.py file and enter your username and password, which can be found on the “My Inbox” page. This will allow Mailtrap to intercept any email sent from your application’s contact form and display it in the dashboard for further inspection. 

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'sandbox.smtp.mailtrap.io'
EMAIL_PORT = 2525
EMAIL_HOST_USER = 'example_username'
EMAIL_HOST_PASSWORD = 'example_password'
EMAIL_USE_TLS = True

If you need a quick visual reminder of the steps necessary to create a contact form in Django, make sure to watch our dedicated video:

Conclusion

With these steps, you’ll be able to develop a reliable and efficient contact form for your website that’ll help you to connect with your users. So go ahead and implement a Django contact form on your website today! And if you need more helpful topics about Django and Python, check these out: 

Article by Denys Kontorskyy Technical Content Writer @Mailtrap

I am an experienced Technical Content Writer specializing in email infrastructure, offering insights on sending, testing, and optimizing emails. I also have a strong interest in product marketing, creating engaging content that drives audience engagement and supports business growth. With a focus on delivering effective campaigns and staying updated with industry trends, I bring a strategic approach to my writing that aims to achieve measurable results.