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.


  • models.py:



          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' % (self.name)
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!!!!'


  • forms.py:


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



  • views.py:


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':
email_form.save()
                                print 'Email template has been updated.'
elif action==u'send_email':
sent = send_email(email_form)
if sent:
print 'Email has been sent.'
                                else:
                                        print 'Fail to sent email.'
return redirect('my_app.views.email_main')
else:
print "email_form not valid!"
else:
email_form = EmailTemplateForm(auto_id='id_notify_%s', instance=email_template)
return render_to_response('email.html', locals(), context_instance=RequestContext(request))



  • utils.py:

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 = 'dangtrinhnt@gmail.com'
      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, \
                                           recipient_list=['nguyentrongdangtrinh@gmail.com',])
             has_sent = True
       return has_sent


  • email.html:


...
{% if email_form %}
<form method='post' action=''>{% csrf_token %}
{{ email_form.name.as_hidden }} <!-- 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>
</form>
{% endif %}
...


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


   


     



Comments