Django "Contact Us" Form

Click on the elements below to interact with them
URLConfViewTemplateFormDjangoSettings

Diagram Overview

This diagram shows the code required to build a simple Contact Us form. This form can be added to any site to allow users to send emails to the company.

You can see the tutorial showing the step by step process to build it at http://...

URL Conf

In this project, there is only one web page. This page has the Contact Us form. We want to make this page available at the /contact-us/ URL. To do this, we need to configure the Django project urls.py file.

Here are the contents of the /.../django_101/core/urls.py file for this project. Note that the /admin/ URL Conf is in the project by default. We are adding just one additional URL Conf.

from django.conf.urls import url
from django.contrib import admin

from myapp.views import contact_us


urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^contact-us/', contact_us, name="contact-us"),
]

View Code

This simple application has but one Django view. This view is responsible for two things:

  1. First, it will render a blank Contact Us form when the /contact-us/ form is first accessed
  2. Second, if a user fills out the form and clicks the Submit button, the view will send an email to the site admin team

This view code will reside in the /.../django_101/myapp/views.py file.

from django.shortcuts import render
from django.http import HttpResponse # Add this
from django.core.mail import send_mail

from .forms import ContactForm # Add this


def contact_us(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            # 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'])

            return HttpResponse('Thanks for contacting us!')
    else:
        form = ContactForm()

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

Template File

In this tutorial we are going to use a very simple templat file. This template is responsible for rendering the Contact Us form on the web page.

Here is the code for the /.../django_101/myapp/templates/myapp.contact-us.html file.

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

Form Class

We will define a simple form class for use in this project. This will make it easy for us to render the form on the web page. It will also provide some useful features, like form validation, without requiring much work.

Open the /.../django_101/myapp/forms.py file.

from django import forms


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

Django Settings

There are two changes to the Django settings.py file that we need to make:

  1. Add the myapp app to the INSTALLED_APPS setting
  2. Add the EMAIL_BACKEND configuration

Open the /.../django_101/core/settings.py file. Here is how you add the two settings above.

#... additional settings above

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp',
]

#... add the following line to the END of the settings.py file
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
Open