Projet

Général

Profil

Télécharger (2,14 ko) Statistiques
| Branche: | Tag: | Révision:

root / corbo / forms.py @ 45b2b19f

1
from django import forms
2
from django.utils.translation import ugettext_lazy as _
3

    
4
from .models import Announce, Category, Broadcast
5
from .channels import get_channel_choices
6

    
7
class AnnounceForm(forms.ModelForm):
8
    transport_channel = forms.MultipleChoiceField(required=False,
9
                                                  choices=get_channel_choices(),
10
                                                  widget=forms.CheckboxSelectMultiple())
11

    
12
    class Meta:
13
        model = Announce
14
        fields = '__all__'
15
        widgets = {
16
            'publication_time': forms.TextInput(attrs={'class': 'datepicker',
17
                                                       'size': 8}),
18
            'expiration_time': forms.TextInput(attrs={'class': 'datepicker',
19
                                                      'size': 8})
20
        }
21
        fields = '__all__'
22

    
23
    def __init__(self, *args, **kwargs):
24
        super(AnnounceForm, self).__init__(*args, **kwargs)
25
        self.fields['transport_channel'].initial = [b.channel for \
26
                                                    b in self.instance.broadcast_set.all()]
27

    
28
    def clean_transport_channel(self):
29
        channels = self.cleaned_data['transport_channel']
30
        limit = 160
31
        if 'sms' in channels and \
32
           len(self.cleaned_data['text']) > limit:
33
            raise forms.ValidationError(_('Announce content exceeds %s chars'
34
                                          ' and cannot be sent by SMS' % limit))
35
        return channels
36

    
37
    def save(self, *args, **kwargs):
38
        instance = super(AnnounceForm, self).save(*args, **kwargs)
39
        if instance:
40
            print "CD: %s" % self.cleaned_data
41
            channels = self.cleaned_data['transport_channel']
42
            for channel in channels:
43
                Broadcast.objects.get_or_create(announce=instance,
44
                                                channel=channel)
45
            self.instance.broadcast_set.exclude(announce=instance,
46
                                                channel__in=channels).delete()
47
        return instance
48

    
49
class CategoryForm(forms.ModelForm):
50
    class Meta:
51
        fields = ('name', )
52
        model = Category
(3-3/11)