Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Django e-mail form example [closed]

I wanted to make a contact form on my website. I can find PHP e-mail forms everywhere, but there are no Django examples. I have no idea how to do it myself, so I'm asking if there is anyone who could tell me from scratch - how to make an e-mail contact form on website using Django?

like image 813
Nhor Avatar asked Feb 09 '15 00:02

Nhor


1 Answers

A simple example could be:

urls.py

from django.conf.urls import patterns, url
from yourapp import views

urlpatterns = patterns(
    '',
    url(r'^email/$',
        views.email,
        name='email'
        ),
    url(r'^thanks/$',
        views.thanks,
        name='thanks'
        ),
)

forms.py

from django import forms

class ContactForm(forms.Form):

    from_email = forms.EmailField(required=True)
    subject = forms.CharField(required=True)
    message = forms.CharField(widget=forms.Textarea)

views.py

from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from yourapp.forms import ContactForm

def email(request):
    if request.method == 'GET':
        form = ContactForm()
    else:
        form = ContactForm(request.POST)
        if form.is_valid():
            subject = form.cleaned_data['subject']
            from_email = form.cleaned_data['from_email']
            message = form.cleaned_data['message']
            try:
                send_mail(subject, message, from_email, ['[email protected]'])
            except BadHeaderError:
                return HttpResponse('Invalid header found.')
            return redirect('thanks')
    return render(request, "yourapp/email.html", {'form': form})

def thanks(request):
    return HttpResponse('Thank you for your message.')

email.html

<form method="post">
    {% csrf_token %}
    {{ form }}
    <div class="form-actions">
      <button type="submit">Send</button>
    </div>
</form>
like image 145
iago1460 Avatar answered Sep 22 '22 15:09

iago1460