summaryrefslogtreecommitdiff
path: root/papillon/polls/forms.py
blob: 3a151aa5933dcc014b07cee057973e77121f0819 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2009  Étienne Loks  <etienne.loks_AT_peacefrogsDOTnet>

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# See the file COPYING for details.

'''
Forms management
'''

from datetime import datetime

from django import forms
from django.contrib.admin import widgets as adminwidgets
from django.utils.translation import gettext_lazy as _

from papillon.polls.models import Poll, Category, Choice, Comment
from papillon import settings

class TextareaWidget(forms.Textarea):
    """
    Manage the edition of a text using TinyMCE
    """
    class Media:
        js = ["%stiny_mce.js" % settings.TINYMCE_URL,
              "%stextareas.js" % settings.MEDIA_URL,]

class PollForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(PollForm, self).__init__(*args, **kwargs)
        self.fields['description'].widget = TextareaWidget()

class CreatePollForm(PollForm):
    class Meta:
        model = Poll
        exclude = ['base_url', 'admin_url', 'open', 'author', 'enddate', 
                    'public', 'opened_admin', 'hide_choices']
        if not Category.objects.all():
            exclude.append('category')

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        exclude = ['date',]
    def __init__(self, *args, **kwargs):
        super(CommentForm, self).__init__(*args, **kwargs)
        self.fields['text'].widget = TextareaWidget()

# workaround for SplitDateTime with required=False
class SplitDateTimeJSField(forms.SplitDateTimeField):
    def __init__(self, *args, **kwargs):
        super(SplitDateTimeJSField, self).__init__(*args, **kwargs)
        self.widget.widgets[0].attrs = {'class': 'vDateField'}
        self.widget.widgets[1].attrs = {'class': 'vTimeField'}

class AdminPollForm(PollForm):
    class Meta:
        model = Poll
        exclude = ['author', 'author_name', 'base_url', 'admin_url',
                   'dated_choices', 'type']
        if not Category.objects.all():
            exclude.append('category')
    enddate = SplitDateTimeJSField(widget=adminwidgets.AdminSplitDateTime(),
        required=False, label=Poll._meta.get_field('enddate').verbose_name,
                        help_text=Poll._meta.get_field('enddate').help_text)

class ChoiceForm(forms.ModelForm):
    class Meta:
        model = Choice
        fields = ('name', 'limit', 'poll', 'order',)
    def __init__(self, *args, **kwargs):
        super(ChoiceForm, self).__init__(*args, **kwargs)
        self.fields['poll'].widget = forms.HiddenInput()
        self.fields['order'].widget = forms.HiddenInput()

class DatedChoiceForm(ChoiceForm):
    def __init__(self, *args, **kwargs):
        super(DatedChoiceForm, self).__init__(*args, **kwargs)
        self.fields['name'].widget = adminwidgets.AdminSplitDateTime()

    def clean_name(self):
        try:
            poll_id = self.data['poll']
            poll = Poll.objects.get(id=int(poll_id))
        except (ValueError, Poll.DoesNotExist):
            raise forms.ValidationError(_('Invalid poll'))
        data = self.cleaned_data['name']
        if poll.dated_choices:
            # management of dates fields
            if data.startswith('[') and data.endswith(']') and "'" in data:
                datas = data.split("'")
                try:
                    assert len(datas) == 5
                    time = datas[3]
                    if not time:
                        time = '00:00:00'
                    date = "%s %s" % (datas[1], time)
                    datetime.strptime(date, '%Y-%m-%d %H:%M:%S') 
                    data = date
                except (ValueError, AssertionError):
                    raise forms.ValidationError(_('Invalid date format: \
YYYY-MM-DD HH:MM:SS'))
        return data

    def clean_limit(self):
        """
        data = eval(self.cleaned_data['name'])
        
                            new_limit = int(request.POST[key])
                            sum = choice.getSum()
                            if new_limit < sum:
                                response_dct['error'] = _("You cannot lower \
%(name)s's limit to this number : there is currently %(sum)d votes for this \
choice.") % {'name':choice.name, 'sum':sum}
                            else:
                                choice.limit = new_limit
                                choice.save()
"""
        pass