forms.py 3.39 KB
Newer Older
Dylann Cordel's avatar
Dylann Cordel committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django import forms
from django.db.models.query import EmptyQuerySet
from django.forms.widgets import Textarea
from django.utils.translation import ugettext_lazy as _

from admin_message.conf import app_settings


###################################################################################################
###################################################################################################
class SendMessageForm(forms.Form):

    class Media:

        js = ('cms/js/libs/jquery.min.js',)

    class ObjetsModelMultipleChoiceField(forms.ModelMultipleChoiceField):
        def label_from_instance(self, obj):
22 23
            final_recipients = self.get_final_recipients(obj)
            nb = len(final_recipients)
Dylann Cordel's avatar
Dylann Cordel committed
24

Dylann Cordel's avatar
wip  
Dylann Cordel committed
25 26 27 28
            if nb is None:
                return _('%s') % obj
            elif not nb:
                return _('%s : no valid recipient') % obj
Dylann Cordel's avatar
Dylann Cordel committed
29
            elif nb == 1:
30
                return '%s : %s' % (obj._meta.verbose_name, final_recipients.items()[0])
Dylann Cordel's avatar
Dylann Cordel committed
31
            else:
Dylann Cordel's avatar
wip  
Dylann Cordel committed
32
                return _('%(type)s « %(name)s » : %(count)d recipients') % {
Dylann Cordel's avatar
Dylann Cordel committed
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
                    'type': obj._meta.verbose_name,
                    'name': obj,
                    'count': nb
                }

    objects = ObjetsModelMultipleChoiceField(
        label="Destinataires",
        widget=forms.CheckboxSelectMultiple,
        queryset=EmptyQuerySet,
        help_text=_("Si vous choisissez de tester cet envoi, l'unique "
                    "destinataire sera vous-même.")
    )

    sender = forms.ChoiceField(
        label=_('sender'),
        choices=[('', _('default'))],
        required=False
    )

    subject = forms.CharField(label=_('Subject'))
    message = forms.CharField(label=_('Message'), widget=Textarea())

55 56 57 58 59
    def __init__(self, queryset, user, message_type, *args, **kwargs):
        self.message_type = message_type
        self.message_type_conf = app_settings.MESSAGE_TYPES[self.message_type]
        senders = self.message_type_conf['get_senders'](user)

Dylann Cordel's avatar
Dylann Cordel committed
60 61 62
        if 'initial' not in kwargs:
            kwargs['initial'] = {}
        if 'message' not in kwargs['initial']:
63
            kwargs['initial']['message'] = self.message_type_conf['get_default_message'](user)
Dylann Cordel's avatar
Dylann Cordel committed
64 65 66
        if 'test_email' not in kwargs['initial'] and user.email in senders:
            kwargs['initial']['test_email'] = user.email
        if queryset and 'objects' not in kwargs['initial']:
67
            kwargs['initial']['objects'] = [obj for obj in queryset.all()]
Dylann Cordel's avatar
Dylann Cordel committed
68 69 70 71

        super(SendMessageForm, self).__init__(*args, **kwargs)

        if queryset:
72 73
            self.fields['objects'].get_final_recipients = self.message_type_conf\
                                                              .get('get_final_recipients')
Dylann Cordel's avatar
Dylann Cordel committed
74
            self.fields['objects'].queryset = queryset
Dylann Cordel's avatar
wip  
Dylann Cordel committed
75 76
        self.fields['sender'].choices = [(value, '%s <%s>' % (label, value))
                                         for value, label in senders.items()]
Dylann Cordel's avatar
Dylann Cordel committed
77

Dylann Cordel's avatar
wip  
Dylann Cordel committed
78 79
    def clean(self):
        super(SendMessageForm, self).clean()
Dylann Cordel's avatar
Dylann Cordel committed
80
        objects = self.cleaned_data['objects']
81
        get_final_recipients = self.message_type_conf['get_final_recipients']
Dylann Cordel's avatar
Dylann Cordel committed
82
        for obj in objects:
83
            recipients = get_final_recipients(obj)
Dylann Cordel's avatar
wip  
Dylann Cordel committed
84 85 86
            if not recipients:
                self.add_error('objects', _('Recipient "%s" has not any valid recipient' % obj))
        return self.cleaned_data