Django contact form tutorial
Let’s build a simple contact form for our Django website. We can take advantage of Django’s built-in email support to make this relatively painless.
Complete working code can for this tutorial can be found on Github at https://github.com/wsvincent/django_contact_form.
First let’s create our virtual environment and install Django:
mkvirtualenv django-contact-form pip install django
Next let’s create a new Django project called django-contact-form and then an app within it called send_email:
django-admin startproject django_contact_form cd django_contact_form python manage.py startapp send_email
To make sure everything installed correctly let’s migrate and then runserver to confirm we see the lovely pastel blue “Welcome to Django” screen:
python manage.py migrate python manage.py runserver
We’ve added an app to our Django project, so add ‘send_email’ at the top of the INSTALLED_APPS section:
# settings.py ... INSTALLED_APPS [ 'send_email', ... ]
And at the bottom of your settings.py file (though really you can place this anywhere) add a line specifying which email backend we’ll use:
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
For now we’ll be outputting our email to the console. Later we can add a few lines to this settings.py file to specify whatever production backend mail server–MailGun, SendGrid, Mandrill, Gmail, etc–we’d like.
Since we’ve added an app to our Django project we need to update the root urls.py file, adding include to the top line and a new urlpattern for the app:
Next create a new file, send_email/urls.py, and add the following code:
Still within our send_email app create a new file, forms.py, which will contain the forms in our actual contact form:
We’re using Django’s built-in Forms API here to quickly create three fields.
Let’s create the view now that will do the bulk of the work for our contact form. Update the existing send_email/views.py file:
There’s a lot going on here! We start by importing send_email and BadHeaderError for security reasons. At the bottom of the imports we reference ContactForm which we just created in our forms.py file.
Final step! We need to create the templates for our email and success pages. Within send_email create a new templates directory and add new files for email.html and success.html:
Success! Email sent.
Send first email
Load http://127.0.0.1:8000/email/ in your web browser, fill out the form, and click the Send button.
You will be redirected to the http://127.0.0.1:8000/success/ if the email goes through.
And in your console you can see that the email was sent: