Django Email and Contact Form Tutorial - Softtalks

Search This Blog

Featured Post

Should you use React Native to build your startup’s mobile app?

Should you use React Native to build your startup’s mobile app? Flexible application improvement is a jumbled system. It requires ...

Monday, April 20, 2020

Django Email and Contact Form Tutorial

Django Email/Contact Form Tutorial

Beginning arrangement

The initial step is to make a devoted catalog for our code. On a Mac, an advantageous area is the Desktop. From the order line, execute the accompanying orders to explore to the Desktop and make another contact envelope.

Django EmailContact Form Tutorial

Django Email/Contact Form Tutorial

$ compact disc ~/Desktop

$ mkdir contact && compact disc contact

Note: If you need assistance extra assistance arranging your Django dev condition, if you don't mind see this establishment direct.

Presently we can introduce Django and initiate our virtual condition.

$ pipenv introduce django==3.0.5

$ pipenv shell

Next how about we make another Django venture called config and inside it an application called send email:

(contact) $ django-administrator startproject config .

(contact) $ python startapp sendemail

To ensure everything introduced effectively we should relocate and afterward runserver.

(contact) $ python move

(contact) $ python runserver

In the event that you open your program to you should see the accompanying screen:

Django Welcome Page


We've made another application so we have to expressly add it to our Django venture. Inside your record, under INSTALLED_APPS include send email at the top.

# config/


'sendemail.apps.SendemailConfig', # new



At that point inside the equivalent record include a line at the end determining which email backend we'll utilize:

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

For the time being, we'll be yielding our email to the order line comfort. Later we can add a couple of lines to this document to determine whatever creation backend mail server- - SendGrid, MailGun, and so on - we'd like.


Since we've added an application to our Django venture we have to refresh the root config/ document, adding incorporate to the top line and another urlpattern for the application:

# config/

from django.contrib import administrator

from django.urls import way, incorporate # new

urlpatterns = [


path('', include('sendemail.urls')), # new


Next make another sendemail/ document in our application.

(contact) $ contact sendemail/

At that point include the accompanying code with the goal that the principle contact structure is at email/and a fruitful accommodation sidetracks to progress/.

# sendemail/

from django.contrib import administrator

from django.urls import way

from .sees import contactView, successView

urlpatterns = [

path('contact/', contactView, name='contact'),

path('success/', successView, name='success'),



Still inside our sendemail application, make another record

(contact) $ contact sendemail/

This will contain the fields in our real contact structure. We'll require three: from_email, subject, and message.

# sendemail/

from django import structures

class ContactForm(forms.Form):

from_email = forms.EmailField(required=True)

subject = forms.CharField(required=True)

message = forms.CharField(widget=forms.Textarea, required=True)

We're utilizing Django's worked in Forms API here to rapidly make three fields.


How about we make the view since will do the greater part of the work for our contact structure. Update the current sendemail/ record:

# sendemail/

from django.core.mail import send_mail, BadHeaderError

from django.http import HttpResponse, HttpResponseRedirect

from django.shortcuts import render, divert

from .structures import ContactForm

def contactView(request):

on the off chance that request.method == 'GET':

structure = ContactForm()


structure = ContactForm(request.POST)

on the off chance that form.is_valid():

subject = form.cleaned_data['subject']

from_email = form.cleaned_data['from_email']

message = form.cleaned_data['message']


send_mail(subject, message, from_email, [''])

aside from BadHeaderError:

return HttpResponse('Invalid header found.')

return redirect('success')

return render(request, "email.html", {'form': form})

def successView(request):

return HttpResponse('Success! Much obliged to you for your message.')

There's a ton going on here! We start by bringing in send_mail and BadHeaderError for security reasons. At the base of the imports we reference ContactForm which we just made in our document.

Make layouts

Last advance! We have to make the layouts for our email and achievement pages. I like to make a task level layouts organizer and put the entirety of my formats in there. So make another index called layouts and make two new records in there.

(contact) $ mkdir formats

(contact) $ contact layouts/email.html

Next update our document to advise Django to glance in this catalog for formats. Update the DIRS settings inside TEMPLATES. This is a one-line change.

# config/

Formats = [



'DIRS': [os.path.join(BASE_DIR, 'templates')],




Presently update our format records with the accompanying code:

<!- - formats/email.html - >

<h1>Contact Us</h1>

<form method="post">

{% crude %}{% csrf_token %}{% endraw %}

{% crude %}{% endraw %}

<div class="form-actions">

<button type="submit">Send</button>



Send first email

Ensure the server is running with python runserver and load your internet browser, round out the structure, and snap the Send button.

Contact Form

You will be diverted to the the email experiences.

Achievement Page

What's more, in your comfort you can see that the email was sent:

(contact) $ python runserver

Looking for record changes with StatReloader

Performing framework checks...

Framework check recognized no issues (0 hushed).

April 17, 2020 - 21:21:53

Django form 3.0.5, utilizing settings 'config.settings'

Beginning advancement server at

Stop the server with CONTROL-C.

[17/Apr/2020 21:21:59] "GET/contact/HTTP/1.1" 200 622

Content-Type: content/plain; charset="utf-8"

Emulate Version: 1.0

Content-Transfer-Encoding: 7bit

Subject: Hello



Date: Fri, 17 Apr 2020 21:22:35 - 0000

Message-ID: <158715855539.8761.15735317856240850309@softtalks-mbp.lan>

Does this email contact structure work?

No comments:

Post a Comment