Blog Home

Django "Contact Us" Tutorial

by -

Here at Diagramy we're working hard to redefine how diagrams are experienced online. To that end, we've created a tool that allows you to design and publish interactive diagrams (like the one below). We have several ideas about how these diagrams can be used. One of them is to support online educational materials, like tutorials and courses.

To demonstrate how interactive diagrams can be used to support tutorials, we've created the below guide. It shows how to build a simple Contact Us form using the Django Framework. Here, the interactive diagram gives an overview of how the backend system works, detailing all of the components and code involved.

We hope you enjoy going through it!

Exploring the Project

There are times when you need a simple Contact Us form on your website. This tutorial will show you how to build such a form using Django. When a user fills out this form and clicks submit, the Django application will send an email of the contact form contents to the address of your choice.

The below diagram shows how this simple application will work. Click the open button, and then click on the components in the diagram to see the code involved. You will learn how to write this code in this tutorial.

Step 1: Setup a Django Project

The first thing we need to do is create a baseline Django project. Follow these steps to do so.

Step 1.1: Create the Project Directory

Open a terminal or command prompt and navigate to a directory that you can complete this course work on. At the terminal execute these commands.

$ mkdir django_101 && cd django_101

Step 1.2: Create and Activate a Virtual Environment

In order to avoid software version conflicts on your computer, it's a best practice to use a tool like Python's Virtualenv to isolate each project into it's own self-contained directory. This will allow you to work on projects without the worry of the components you install conflicting with anything else.

Follow these steps to install and setup the virutal environment.

# if you don't have virtualenv installed, run this command first
$ pip install virtualenv

# create the virtualenv (this will create a folder named 'venv' in the dir)
$ virtualenv venv

# activate the virtualenv on a Mac
$ source venv/bin/activate

# activate the virtualenv on Windows
$ venv/bin/activate.bat

Step 1.3: Install Django

With the virtualenv activated you can now install Django. At the terminal issue the following command. This will install version 1.11 of Django.

# install Django 
$ pip install Django

Step 1.4: Create the Django Project

The starting point to creating Django apps is to create a Django project. Creating a project will place several files and directories into our home directory. These are the basic components of every Django project.

At the terminal execute these commands.

# create the django project
$ django-admin.py startproject core .

This will create a folder named 'core' in the 'django_101' directory. It will also place a file named 'manage.py' in the directory.

Step 1.5: Create the Database

Most Django projects will need a database. Technically, you could use Django without a database. However, most of its features would be unusable. Therefore you will perform this step for virtually every project you work on.

At the terminal execute this command.

# commit the migration
$ python manage.py migrate

Issuing this command will create a database and set of tables required for Django to work.

Step 1.6: Create a Superuser

Django has the concept of a 'superuser'. This user account has all permissions to the application and database actions. When you create a super user you'll specify a username, email address, and password. You'll want to complete this step for your projects and remember the credentials you created.

At the terminal execute this command.

$ python manage.py createsuperuser

Step 1.7: Create a Django App

With the project setup and superuser created, we can move onto creating the first app. With the terminal open enter these commands.

# check working directory
$ pwd
/.../django_101/

# Create the app
$ python manage.py startapp myapp

Step 1.8: Add the App to the Project

After you create an app, you have to update the project settings file to tell Django that the app exists.

This is a great time to introduce the settings.py file. Django uses the settings.py file to store important configuration information about the project. Things like database settings, secret keys, and apps are stored here.

Open django_101/settings.py and add 'myapp' to the INSTALLED_APPS list, it should look like this:

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp',
)

Step 1.9: Run the server

You've completed the setup! Now you can start Django's development server to test if you've done everything correctly.

At the terminal execute this command.

# start the development server
$ python manage.py runserver

Open a web browser and navigate to http://127.0.0.1:8000/. If you see a page that says "Congratulations" everything has been setup properly.

Step 2: Build the "Contact Us" Page

Now that we have a working Django project, it's time to actually write the code for the "Contact Us" page. Follow these steps to build the page.

Step 2.1: Build the Contact Form

Forms are created within an app's directory in a file named forms.py. This file isn't created by default - it has to be manually created. Once created, forms are defined by creating Python classes and subclassing Django's forms class.

After creating the class, the next step is to create form fields. Form fields are created as attributes of the class. The attributes are classed from Django's Form fields library.

Let's create the contact form. Create a file named myapp/forms.py and open it for editing. Add the below code.

from django import forms

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

Code Review
The above code creates a form named 'ContactForm'. It's important to see that this form is subclassed from Django's 'form' class. This is a requirement.

This form has three fields; name, email, and message. Each of these fields is based on attributes of Django's form class. You can see a full list of field types here.

Step 2.2: Import the Contact Form Into Views.py

Our goal is to use the form class created in the previous step in a view. Therefore we need to import it into our views.py file. Open the 'myapp/views.py' file and add the forms import statement to the file as follows. You'll also need to add the HttpResponse import.

from django.shortcuts import render
from django.views.generic import View
from django.http import HttpResponse # Add this

from .forms import ContactForm # Add this

Step 2.3: Add the Form to the Function Based View

Locate the view in the views.py file. Update it as follows.

def contact_us(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            # send email code goes here
            return HttpResponse('Thanks for contacting us!')
    else:
        form = ContactForm()

    return render(request, 'myapp/contact-us.html', {'form': form})

Code Review
The above code is the basic structure required for form processing in a function based view. It consists of an Python If...Else... statement.

When you fill out a form in a browser and click submit, the browser will by default package the form data and perform an HTTP POST operation to the server. That's why our code does the check if request.method == 'POST'; we're testing to see if the user is submitting form. If they aren't submitting the form, then we assume it is a HTTP GET request and proceed to render a blank form.

Step 2.4: Add the Form in the Contact Us Template

Next, we need to add the form object to our template.

Open myapp/templates/myapp/contact-us.html and add the following beneath the <p> element and before the </body>

<h2>Contact Us</h2>
<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Submit" />
</form>

Step 2.5: Test the Form

Go to your terminal, start the development server, and then ppen a browser and go to http://127.0.0.1:8000/contact-us/ where by you will see the form on the page.

Click the submit button without filling any form fields. You should see errors saying This is a required field. This is a feature of the Django Form API called validation.

Now, fill out all the fields and click submit. If everything is working you should now see a message that says that "Thanks for contacting us!".

Step 2.6: Sending an Email with the Form Information

The first thing to update is something called the 'email backend'. This is a setting that tells Django how to send email. As this is a development environment, we are going to make emails appear in our terminal/command prompt window. This means an email won't actually be sent, rather you'll be able to look at your terminal to see it.

Open django_101/core/settings.py for editing and add this line to the end of the file:

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

With that done we can now edit the views with the proper code to send the email. Open myapp/views.py for editing. First, add one import to the top of the 'views.py' file.

from django.core.mail import send_mail

Then, locate the # send email code goes here comment and add this code. Be sure to change the email address to your own.

# send email code goes here
sender_name = form.cleaned_data['name']
sender_email = form.cleaned_data['email']

message = "{0} has sent you a new message:\n\n{1}".format(sender_name, form.cleaned_data['message'])
send_mail('New Enquiry', message, sender_email, ['enquiry@exampleco.com'])

With that done you should be able to fill out the form form, click submit, and check your inbox for an email message.

Step 2.7: Verify Your Work

Now it's time to check your work. First, start the development server:

# make sure you're in django_101
$ pwd
/.../django_101

# start the sever
$ python manage.py runserver

Then, open http://127.0.0.1:8000/contact-us/, fill out the form, and click the submit button. Look at your termina/command prompt; it should look like this:

System check identified no issues (0 silenced).
December 14, 2015 - 19:57:33
Django version 1.9, using settings 'core.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

[14/Dec/2015 19:57:34] "GET /contact-us/ HTTP/1.1" 200 665

MIME-Version: 1.0
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 7bit
Subject: New Enquiry
From: someone_xxxx@gmail.com
To: enquiry@exampleco.com
Date: Mon, 14 Dec 2015 19:57:39 -0000
Message-ID: <20151214195739.2055.29841@revomac.local>

Thomas J. has sent you a new message:

Great Site!

-------------------------------------------------------------------------------
[14/Dec/2015 19:57:40] "POST /contact-us/ HTTP/1.1" 200 25

Add a Comment

Please Sign Up or Sign In to leave a comment.