How To: Django Contact Form

06/09/2019 12:06 by Dominic DiTaranto
34

So I have just recently started learning Django. Coming from Flask, almost all aspects of it have been quite simple to figure out. Of course, Corey Schafer's Django tutorial series is my go to guide. 

I am currently developing a website for a non-profit organization supporting those with allergies in New Jersey. I needed to create a contact form and assumed it would be an easy task, considering I have done it in Flask many times. I watched a few YouTube videos, looked at some stack exchange posts and got many different explanations, even one video only showing how users can send their message directly to a database instead of sending it as an email. 

Anyway, because I was unable to find a concise explanation easily, I will offer my solution (an amalgamation of a few YouTube videos and blog posts I just learned from) here for those who want the quick and dirty way of handling a contact form in Django.

1. Setup

I am not going to go through the preliminary steps of setting up a Django application, so let's get straight into the configuration of the email.

In your settings.py file add these lines of code and configure them to your needs:

EMAIL_USE_TLS = True
EMAIL_HOST = 'Your Email Host'
EMAIL_PORT = Email Port Number
EMAIL_HOST_USER = 'Your Email Address'
EMAIL_HOST_PASSWORD = 'Your Email Password'

**The  TLS setting and PORT setting will vary depending on your email host. But if you are planning on using gmail, this would be the proper configuration:

EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'youremail@gmail.com'
EMAIL_HOST_PASSWORD = 'PASSWORD'

Furthermore, we should not be storing password and email addresses like this. I suggest you use environment variables instead to properly hide sensitive data. A proper explanation of the implementation of environment variables is beyond the scope of this tutorial, but I do recommend you check out this video to learn more.

2. Forms

In your app directory, create a file named forms.py and add this snippet of code:

from django import forms


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

Here we will ask the user for their name, email, the subject of their message and the actual content of the message itself.

3. Views

In your views you need to add these imports:

from django.shortcuts import render, redirect
from django.core.mail import send_mail
from .forms import Contact

We will be using this send_mail() function from django.core.mail to send the email retrieved from the form filled out by the user. Its documentation can be found here: https://docs.djangoproject.com/en/2.2/topics/email/#send-mail

Now we need to create the view for the contact form.

def contact(request):

    if request.method == 'POST':
        form = Contact(request.POST)

        if form.is_valid():

            message = """ 
            From: %s <%s>
            %s
            """ % (form.data['name'], form.data['email'], form.data['message'])

            send_mail(
                form.data['subject'],
                message,
                form.data['email'],
                ['domdit@gmail.com'],
                fail_silently=False
            )

            return redirect('index')

    else:
        form = Contact()

    context = {
        'form': form,
    }

    return render(request, 'contact.html', context)

In the view we are checking first whether or not the request method was POST. If it is, we make sure that the form was filled out correctly with the if_valid() function. then we create the body of the message. It is important to note that I am using the old style of string formatting here by using the % operator. This is just my own personal preference. the send_mail() function does not include an argument for the user's name, so instead we add it to the message variable, along with their email next to it (for safe keeping and easy readability), and then on the next line we add the complete message itself.

After calling the send_mail(subject, message, email_of_user, your_email) function, we redirect the user to whatever view you so please. here I am sending them to the index, and will probably flash a message saying "Message Successfully Sent!" (will be added in Part 2)

4. Template

The contact template is just as easy as the previous steps. Just create a contact.html file in your app/templates directory and copy-paste this in there.

<h1>Contact</h1>
<form role="form" action="" method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Submit</button>
</form>

{{ form.as_p }} puts each form field into a <p> tag, but you should check out Crispy-Forms for better ways to style your form fields!

And that is it. You can now have users send you an email.  

Category: Coding
Tags: Python, Django, Contact, Email

Comments(0):

Be the first to leave a comment!

Leave a Comment:
:
Previous Post

DOMDIT.COM

Hello and welcome to my blog. I am planning to post from a myriad of different topics including: coding, translations, reflections on books I am currently reading, music that I am writing, photography, as well as personal topics/events that may creep in once in a while. To learn more about me, you can visit the main page of this website here, or you can always comment on one of my posts and I will get back to you!

Recent Posts:

How To: Django Contact Form
06/09/2019 12:06
Asteroids in p5.js
06/08/2019 08:30
First Post
05/08/2019 11:50

Popular Posts:

First Post
05/08/2019 11:50
Asteroids in p5.js
06/08/2019 08:30
How To: Django Contact Form
06/09/2019 12:06

Recent Categories:

  • Coding

  • Recent Tags:

    Asteroids Contact Contact Form Django Email First-Post! Flask Jinja2 Python SQLAlchemy Web Development javascript music p5.js
    Powered by Alambi | Designed by Dominic DiTaranto © 2019