Source

django-informativo / informativo / forms.py

Full commit
from django import forms
from django.utils.translation import ugettext_lazy as _

from informativo.models import Contact, MailingList


def _get_mailinglists_choices():
    mailing_lists = [(m.pk, m.name) for m in MailingList.objects.all()]
    mailing_lists.insert(0, (0, _('All')))
    return mailing_lists


class SubscribeForm(forms.Form):
    first_name = forms.CharField(label=_('First name'), required=False)
    last_name = forms.CharField(label=_('Last name'), required=False)
    email = forms.EmailField(label=_('E-mail'), required=True)
    mailing_lists = forms.MultipleChoiceField(
        label=_('Mailing lists'),
        initial=[0],
        widget=forms.CheckboxSelectMultiple
    )

    def __init__(self, *args, **kwargs):
        super(SubscribeForm, self).__init__(*args, **kwargs)
        self.fields['mailing_lists'].choices = _get_mailinglists_choices()

    def subscribe(self):
        mailing_lists = self.cleaned_data['mailing_lists']
        if '0' in mailing_lists:
            subscribe_list = MailingList.objects.all()
        else:
            subscribe_list = MailingList.objects.filter(pk__in=mailing_lists)

        contact, created = Contact.objects.get_or_create(
            email=self.cleaned_data['email'],
            defaults={
                'first_name': self.cleaned_data['first_name'],
                'last_name': self.cleaned_data['first_name'],
            }
        )

        if created:
            contact.mailing_lists = subscribe_list
        else:
            contact.mailing_lists.add(*subscribe_list)

        contact.save()
        return contact


class UnsubscribeForm(forms.Form):
    email = forms.EmailField(label=_('E-mail'), max_length=100)
    mailing_lists = forms.MultipleChoiceField(
        label=_('Mailing lists'),
        initial=[0],
        widget=forms.CheckboxSelectMultiple
    )

    def __init__(self, *args, **kwargs):
        super(UnsubscribeForm, self).__init__(*args, **kwargs)
        self.fields['mailing_lists'].choices = _get_mailinglists_choices()

    def clean_email(self):
        data = self.cleaned_data.get('email')
        try:
            self._contact = Contact.objects.get(email=data)
        except:
            msg = _('This e-mail does not exist in our database.')
            raise forms.ValidationError(msg)
        return data

    def unsubscribe(self):
        email = self.cleaned_data['mailing_lists']
        mailing_lists = self.cleaned_data['mailing_lists']
        if '0' in mailing_lists:
            self._contact.mailing_lists.clear()
        else:
            unsubscribe_list = MailingList.objects.exclude(pk__in=mailing_lists)
            self._contact.mailing_lists.remove(*unsubscribe_list)
        return self._contact