Django sending email

building and small webpage and in that page I want an small contact field. So my visitors (if any ) can contact me with an form input.
So I made an small html template that has a very small form (No validation ) and then post the email and massages back to the view that send the email.
small and simple and today work in front of the tv.

django template my template extends my index as you see called contact.html

{% extends "index.html" %}

{% block content %}</pre>
<div class="container">
<h2>Contact</h2>
<form action="#" method="post">{% csrf_token %} <input type="text" name="email" placeholder="You Email" />
<textarea name="message" rows="3">Message</textarea>
<button class="btn" type="submit">Send</button></form></div>
{% endblock %}

And urls.py entory to handel the request

url(r'^contact$', 'search.views.contact', name='contact'),

Then the matching view

def contact(request):
	c = {}
	c.update(csrf(request))

	if request.method == 'POST':
		incommingemail=request.POST["email"]
		incommingmessage=request.POST["message"]
		subject="Contact from taxering"
		if incommingemail and incommingmessage:
			try:
   				send_mail(subject, incommingmessage, incommingemail, ['info@test.com'])
			except BadHeaderError:
   				return HttpResponse('Invalid header found.')
			return HttpResponseRedirect('/thanks/')

	return render_to_response('contact.html',context_instance=RequestContext(request))

then an new template for thanking the user for contacting me called thanks.html

{% extends "index.html" %}
{% block content %}
<h2>Thank you</h2>
We will contact you shortly {% endblock %}

and matching url in the urls.py file for thanks.

url(r'^thanks$', 'search.views.thanks', name='thanks'),

And the view for saying thanks

def thanks(request):
	'''
	Thanks you for contact us
	'''
	return render_to_response('thanks.html',context_instance=RequestContext(request))

So all done

Leave a Reply

%d bloggers like this: