Here's a basic version using a class based view for a contact page. It shows a success message above the original form.
mywebapp/forms.py
### forms.py
from django import forms
class ContactForm(forms.Form):
contact_name = forms.CharField(label='Your Name', max_length=40, required=True)
contact_email = forms.EmailField(label='Your E-Mail Address', required=True)
content = forms.CharField(label='Message', widget=forms.Textarea, required=True)
mywebapp/views.py
### views.py
from django.contrib.messages.views import SuccessMessageMixin
from django.core.mail import EmailMessage
from django.core.urlresolvers import reverse_lazy
from django.template.loader import get_template
from django.views.generic import TemplateView, FormView
from mywebapp.forms import ContactForm
class ContactView(SuccessMessageMixin, FormView):
form_class = ContactForm
success_url = reverse_lazy('contact')
success_message = "Your message was sent successfully."
template_name = 'contact.html'
def form_valid(self, form):
contact_name = form.cleaned_data['contact_name']
contact_email = form.cleaned_data['contact_email']
form_content = form.cleaned_data['content']
to_recipient = ['Jane Doe <[email protected]>']
from_email = 'John Smith <[email protected]>'
subject = 'Website Contact'
template = get_template('contact_template.txt')
context = {
'contact_name': contact_name,
'contact_email': contact_email,
'form_content': form_content
}
content = template.render(context)
email = EmailMessage(
subject,
content,
from_email,
to_recipient,
reply_to=[contact_name + ' <' +contact_email + '>'],
)
email.send()
return super(ContactView, self).form_valid(form)
templates/contact.html
### templates/contact.html
{% extends 'base.html' %}
{% block title %}Contact{% endblock %}
{% block content %}
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
<form role="form" action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
{% endblock %}
templates/contact_template.txt
### templates/contact_template.txt
### used to render the body of the email
Contact Name: {{contact_name}}
Email: {{contact_email}}
Content: {{form_content}}
config/urls.py
### config/urls.py
from mywebapp.views import *
urlpatterns = [
url(r'^about/', AboutView.as_view(), name='about'),
url(r'^contact/$', ContactView.as_view(), name='contact'),
url(r'^$', IndexView.as_view()),
]