models.py 2.24 KB
Newer Older
1 2
# -*- coding: utf8 -*-

fred's avatar
fred committed
3 4
import hashlib
import random
5
import subprocess
fred's avatar
fred committed
6

7
from django.db import models
jean-philippe's avatar
jean-philippe committed
8 9 10 11

from django.template import loader, Context 
from django.conf import settings

12 13
from django.utils.translation import ugettext
from django.utils.translation import ugettext_lazy as _
14
from django.core.mail import send_mail
15 16 17

from ckeditor.fields import RichTextField

18 19 20 21 22 23

class Subscriber(models.Model) :
    email = models.EmailField(unique = True)   # TODO : informer si déjà inscrit ? Que faire dans ce cas.
    inscription_date = models.DateField(auto_now_add=True)
    is_validated = models.NullBooleanField() # Au click sur le lien de confirmation. Null si erreur à l'envoi au souscripteur.
    is_registered = models.NullBooleanField() # À l'inscription après la confirmation Null si erreur à l'envoi à mailman.
24 25
    password = models.CharField(max_length=100) # sha1
    
26 27 28 29 30
    def __unicode__(self) :
        return self.email

    def save(self, *args, **kwargs):
        super(Subscriber, self).save(*args, **kwargs)
jean-philippe's avatar
jean-philippe committed
31
        if self.is_validated is None:
fred's avatar
fred committed
32 33 34 35 36 37
            self.send_confirmation_email()

    def send_confirmation_email(self):
        self.password = hashlib.sha1(str(random.random())).hexdigest()
        confirm_subject = loader.get_template('newsletter/confirmation_email_subject.txt')
        confirm_body = loader.get_template('newsletter/confirmation_email_body.txt')
fred's avatar
fred committed
38
        context = Context({'token': self.password})
fred's avatar
fred committed
39 40 41
        send_mail(confirm_subject.render(context).strip(), confirm_body.render(context),
                settings.NEWSLETTER_SENDER, [self.email])
        self.is_validated = False
jean-philippe's avatar
jean-philippe committed
42
        self.save()
fred's avatar
fred committed
43 44

    def subscribe_in_mailman(self):
45 46 47
        t = subprocess.call(['listadmin', '--add-member', self.email, settings.NEWSLETTER_NAME])
        if t != 0:
            return
fred's avatar
fred committed
48
        self.is_registered = True
49
        self.save()
50 51 52 53 54 55 56 57 58 59 60 61 62 63


class Newsletter(models.Model):

    class Meta:
        verbose_name = _('Newsletter')
        verbose_name_plural = _('Newsletters')
        ordering = ['date']

    subject = models.CharField(_('Title'), max_length=50)
    date = models.DateField(_('Date'))
    text = RichTextField(_('Text'), null=True, blank=True)

    expedition_datetime = models.DateTimeField(_('Expedition Date/time'), null=True, blank=True)