Friday, April 26, 2013

Sending email with template using model form (also update template in the same view) in Django

Here is the technique that I use when sending email with template using Django model form. It also gives me the ability to update the model in the same view with the email form.


          from django.db import models
class EmailTemplate(models.Model):
name = models.CharField(max_length=50)
subject = models.CharField(max_length=255)
template = models.TextField()
def __unicode__(self):
return u'%s' % (
class Meta:
ordering = ['name']

Assuming I have created a template instance in the admin interface with:
- name = 'my_template'
- subject = 'This is my email template subject'
- template = 'Helly {{my_name}}, This is my email. Geniusss!!!!'


from django.forms import ModelForm
class EmailTemplateForm(ModelForm):
class Meta:
model = EmailTemplate


from my_app.models import EmailTemplate
from my_app.utils import 

def email_main(request):
email_template = EmailTemplate.objects.get(name='my_template')
if request.method=='POST':
action = request.POST.get('action')
email_form = EmailTemplateForm(request.POST, request.FILES,\
instance=email_template, auto_id='id_notify_%s')
if email_form.is_valid():
if action==u'update_email_template':
                                print 'Email template has been updated.'
elif action==u'send_email':
sent = send_email(email_form)
if sent:
print 'Email has been sent.'
                                        print 'Fail to sent email.'
return redirect('my_app.views.email_main')
print "email_form not valid!"
email_form = EmailTemplateForm(auto_id='id_notify_%s', instance=email_template)
return render_to_response('email.html', locals(), context_instance=RequestContext(request))


from django.core.mail import send_mail
# here is where you insert specific information to the token inside the email template
def complete_email_body(message):
      result = False
      if '{{my_name}}' in message:
            message = message.replace('{{my_name}}', 'Trinh Nguyen')
       return message, result

def send_email(email_form):
      from_email = ''
      has_sent = False
      subject = email_form.cleaned_data['subject']
      message, result = complete_email_body(email_form.cleaned_data['template'])
      if result:
            send_mail(subject=subject, message=message, from_email=from_email, \
             has_sent = True
       return has_sent

  • email.html:

{% if email_form %}
<form method='post' action=''>{% csrf_token %}
{{ }} <!-- It is a must -->
Subject: {% email_form.subject.errors %}
{% email_form.subject %}
Message: {% email_form.template.errors %}
{% email_form.template %}
<button type="submit" name="action" value="update_email_template">Save</button>
<button type="submit" name="action" value="send_email">Send</button>
{% endif %}

And It works like a charm! BTW, It's FRIDAYYYYYY!!!!!!!