Contact form

In this article I will briefly describe mechanisms behind Contact Form. It is bootstrap form that sends POST requests to Django which uses SendGrid smtp server to send the emails.

    1.Lets have a look at

from django.shortcuts import render, redirect
from django.core.mail import BadHeaderError, send_mail
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib import messages

def contact(request):
    if request.method == 'POST':
        subject = request.POST.get('subject')
        message = request.POST.get('message')
        email = request.POST.get('email')

        if subject and message and email:
                send_mail('Sent from '\
+subject, message, email, [''],fail_silently= True)
            except BadHeaderError:
                return HttpResponse('{Bad Header}')
            return greatsuccess(request)
            return HttpResponse('{Invalid Form}')
    return render(request, 'personal/contact.html')

So how it works? We are first checking if there are any POST requests and returning website render if there are none. If we have "subject and message and email" we are trying to send email using django send_email function. We are also defining views for BadHeaderError and invalid form, this is all for security. I am also using django messages for success view, this will all become clear when you see my template.

For more information on this view, please check this article. 

    2.Template (again extending main view)

<div class="form-area">  
        <form role="form" method="POST">
          {% csrf_token %}
           <input type="text" class="form-control" id="subject" 
name="subject" placeholder="Subject" maxlength="70" required>
                    <div class="form-group">
            <input type="email" class="form-control" id="email" 
name="email" placeholder="Email" required>
                    <div class="form-group">
            <textarea class="form-control" type="textarea" id="message" 
name="message" placeholder="Message" maxlength="300" rows="7"></textarea>                
        <button type="submit"  name="submit" 
class="btn btn-m btn-secondary">Submit</button>


{% for message in messages %}
        Email sent
        {% endfor %}

This template doesn't require that many tags as we are basing everything on POST requests that are part of HTML. We have our obligatory csrf token inside the form as well as loop for messages, this will display "Email sent" text below the form once an email has been sent.

EMAIL_HOST = 'xxx'

In settings we need to specify our email host. I am personally using SendGrid as it is free service.

    4.What are my upgrade plans

I will have to add captcha to the form as I might get some spam through the form. I will also try to extend my success view and maybe add some disappearing javascript bar. I might add copy of the email sent to the sender as well as for now this is only going to me. There are plenty of cool things that can be added :)