]> git.openstreetmap.org Git - osqa.git/blob - forum/forms.py
143be75c7db5fa007dd073f6e6ad51ff37df2446
[osqa.git] / forum / forms.py
1 import re
2 from datetime import date
3 from django import forms
4 from models import *
5 from django.utils.translation import ugettext as _
6 from django.contrib.humanize.templatetags.humanize import apnumber
7 from forum.models import User
8
9 from django.utils.safestring import mark_safe
10 from forum.utils.forms import NextUrlField, UserNameField, SetPasswordForm
11 from forum import settings
12 import logging
13
14 class TitleField(forms.CharField):
15     def __init__(self, *args, **kwargs):
16         super(TitleField, self).__init__(*args, **kwargs)
17         self.required = True
18         self.widget = forms.TextInput(attrs={'size' : 70, 'autocomplete' : 'off'})
19         self.max_length = 255
20         self.label  = _('title')
21         self.help_text = _('please enter a descriptive title for your question')
22         self.initial = ''
23
24     def clean(self, value):
25         if len(value) < settings.FORM_MIN_QUESTION_TITLE:
26             raise forms.ValidationError(_('title must be must be at least %s characters' % settings.FORM_MIN_QUESTION_TITLE))
27
28         return value
29
30 class EditorField(forms.CharField):
31     def __init__(self, *args, **kwargs):
32         super(EditorField, self).__init__(*args, **kwargs)
33         self.required = True
34         self.widget = forms.Textarea(attrs={'id':'editor'})
35         self.label  = _('content')
36         self.help_text = u''
37         self.initial = ''
38
39     def clean(self, value):
40         if len(value) < settings.FORM_MIN_QUESTION_BODY and not settings.FORM_EMPTY_QUESTION_BODY:
41             raise forms.ValidationError(_('question content must be must be at least %s characters' % settings.FORM_MIN_QUESTION_BODY))
42
43         return value
44
45 class TagNamesField(forms.CharField):
46     def __init__(self, *args, **kwargs):
47         super(TagNamesField, self).__init__(*args, **kwargs)
48         self.required = True
49         self.widget = forms.TextInput(attrs={'size' : 50, 'autocomplete' : 'off'})
50         self.max_length = 255
51         self.label  = _('tags')
52         #self.help_text = _('please use space to separate tags (this enables autocomplete feature)')
53         self.help_text = _('Tags are short keywords, with no spaces within. At least one %(min)s and up to %(max)s tags can be used.') % {
54             'min': apnumber(settings.FORM_MIN_NUMBER_OF_TAGS), 'max': apnumber(settings.FORM_MAX_NUMBER_OF_TAGS)    
55         }
56         self.initial = ''
57
58     def clean(self, value):
59         value = super(TagNamesField, self).clean(value)
60         data = value.strip()
61
62         split_re = re.compile(r'[ ,]+')
63         list = split_re.split(data)
64
65         if len(list) > settings.FORM_MAX_NUMBER_OF_TAGS or len(list) < settings.FORM_MIN_NUMBER_OF_TAGS:
66             raise forms.ValidationError(_('please use between %(min)s and %(max)s tags') % { 'min': apnumber(settings.FORM_MIN_NUMBER_OF_TAGS), 'max': apnumber(settings.FORM_MAX_NUMBER_OF_TAGS)})
67
68         list_temp = []
69         tagname_re = re.compile(r'[a-z0-9]+')
70         for tag in list:
71             test = len(tag)
72             if len(tag) > settings.FORM_MAX_LENGTH_OF_TAG or len(tag) < settings.FORM_MIN_LENGTH_OF_TAG:
73                 raise forms.ValidationError(_('please use between %(min)s and %(max)s characters in you tags') % { 'min': apnumber(settings.FORM_MIN_LENGTH_OF_TAG), 'max': apnumber(settings.FORM_MAX_LENGTH_OF_TAG)})
74             if not tagname_re.match(tag):
75                 raise forms.ValidationError(_('please use following characters in tags: letters \'a-z\', numbers, and characters \'.-_#\''))
76             # only keep one same tag
77             if tag not in list_temp and len(tag.strip()) > 0:
78                 list_temp.append(tag)
79
80         return u' '.join(list_temp)
81
82 class WikiField(forms.BooleanField):
83     def __init__(self, *args, **kwargs):
84         super(WikiField, self).__init__(*args, **kwargs)
85         self.required = False
86         self.label  = _('community wiki')
87         self.help_text = _('if you choose community wiki option, the question and answer do not generate points and name of author will not be shown')
88     def clean(self,value):
89         return value and settings.WIKI_ON
90
91 class EmailNotifyField(forms.BooleanField):
92     def __init__(self, *args, **kwargs):
93         super(EmailNotifyField, self).__init__(*args, **kwargs)
94         self.required = False
95         self.widget.attrs['class'] = 'nomargin'
96
97 class SummaryField(forms.CharField):
98     def __init__(self, *args, **kwargs):
99         super(SummaryField, self).__init__(*args, **kwargs)
100         self.required = False
101         self.widget = forms.TextInput(attrs={'size' : 50, 'autocomplete' : 'off'})
102         self.max_length = 300
103         self.label  = _('update summary:')
104         self.help_text = _('enter a brief summary of your revision (e.g. fixed spelling, grammar, improved style, this field is optional)')
105
106
107 class FeedbackForm(forms.Form):
108     name = forms.CharField(label=_('Your name:'), required=False)
109     email = forms.EmailField(label=_('Email (not shared with anyone):'), required=False)
110     message = forms.CharField(label=_('Your message:'), max_length=800,widget=forms.Textarea(attrs={'cols':60}))
111     next = NextUrlField()
112
113 class AskForm(forms.Form):
114     title  = TitleField()
115     text   = EditorField()
116     tags   = TagNamesField()
117     wiki = WikiField()
118
119
120 class AnswerForm(forms.Form):
121     text   = EditorField()
122     wiki   = WikiField()
123
124     def __init__(self, question, *args, **kwargs):
125         super(AnswerForm, self).__init__(*args, **kwargs)
126
127         if question.wiki and settings.WIKI_ON:
128             self.fields['wiki'].initial = True
129
130
131 class RetagQuestionForm(forms.Form):
132     tags   = TagNamesField()
133     # initialize the default values
134     def __init__(self, question, *args, **kwargs):
135         super(RetagQuestionForm, self).__init__(*args, **kwargs)
136         self.fields['tags'].initial = question.tagnames
137
138 class RevisionForm(forms.Form):
139     """
140     Lists revisions of a Question or Answer
141     """
142     revision = forms.ChoiceField(widget=forms.Select(attrs={'style' : 'width:520px'}))
143
144     def __init__(self, post, *args, **kwargs):
145         super(RevisionForm, self).__init__(*args, **kwargs)
146
147         revisions = post.revisions.all().values_list(
148             'revision', 'author__username', 'revised_at', 'summary')
149         date_format = '%c'
150         self.fields['revision'].choices = [
151             (r[0], u'%s - %s (%s) %s' % (r[0], r[1], r[2].strftime(date_format), r[3]))
152             for r in revisions]
153
154         self.fields['revision'].initial = post.active_revision.revision
155
156 class EditQuestionForm(forms.Form):
157     title  = TitleField()
158     text   = EditorField()
159     tags   = TagNamesField()
160     summary = SummaryField()
161
162     def __init__(self, question, revision=None, *args, **kwargs):
163         super(EditQuestionForm, self).__init__(*args, **kwargs)
164
165         if revision is None:
166             revision = question.active_revision
167
168         self.fields['title'].initial = revision.title
169         self.fields['text'].initial = revision.body
170         self.fields['tags'].initial = revision.tagnames
171             
172         # Once wiki mode is enabled, it can't be disabled
173         if not question.wiki:
174             self.fields['wiki'] = WikiField()
175
176 class EditAnswerForm(forms.Form):
177     text = EditorField()
178     summary = SummaryField()
179
180     def __init__(self, answer, revision=None, *args, **kwargs):
181         super(EditAnswerForm, self).__init__(*args, **kwargs)
182
183         if revision is None:
184             revision = answer.active_revision
185
186         self.fields['text'].initial = revision.body
187
188 class EditUserForm(forms.Form):
189     email = forms.EmailField(label=u'Email', help_text=_('this email does not have to be linked to gravatar'), required=True, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
190     realname = forms.CharField(label=_('Real name'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
191     website = forms.URLField(label=_('Website'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
192     city = forms.CharField(label=_('Location'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
193     birthday = forms.DateField(label=_('Date of birth'), help_text=_('will not be shown, used to calculate age, format: YYYY-MM-DD'), required=False, widget=forms.TextInput(attrs={'size' : 35}))
194     about = forms.CharField(label=_('Profile'), required=False, widget=forms.Textarea(attrs={'cols' : 60}))
195
196     def __init__(self, user, *args, **kwargs):
197         super(EditUserForm, self).__init__(*args, **kwargs)
198         if settings.EDITABLE_SCREEN_NAME:
199             self.fields['username'] = UserNameField(label=_('Screen name'))
200             self.fields['username'].initial = user.username
201             self.fields['username'].user_instance = user
202         self.fields['email'].initial = user.email
203         self.fields['realname'].initial = user.real_name
204         self.fields['website'].initial = user.website
205         self.fields['city'].initial = user.location
206
207         if user.date_of_birth is not None:
208             self.fields['birthday'].initial = user.date_of_birth
209         else:
210             self.fields['birthday'].initial = '1990-01-01'
211         self.fields['about'].initial = user.about
212         self.user = user
213
214     def clean_email(self):
215         """For security reason one unique email in database"""
216         if self.user.email != self.cleaned_data['email']:
217             #todo dry it, there is a similar thing in openidauth
218             if settings.EMAIL_UNIQUE == True:
219                 if 'email' in self.cleaned_data:
220                     try:
221                         user = User.objects.get(email = self.cleaned_data['email'])
222                     except User.DoesNotExist:
223                         return self.cleaned_data['email']
224                     except User.MultipleObjectsReturned:
225                         raise forms.ValidationError(_('this email has already been registered, please use another one'))
226                     raise forms.ValidationError(_('this email has already been registered, please use another one'))
227         return self.cleaned_data['email']
228
229 NOTIFICATION_CHOICES = (
230     ('i', _('Instantly')),
231     ('d', _('Daily')),
232     ('w', _('Weekly')),
233     ('n', _('No notifications')),
234 )
235
236 class SubscriptionSettingsForm(forms.Form):
237     member_joins = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
238     new_question = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
239     new_question_watched_tags = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
240     subscribed_questions = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
241
242     all_questions = forms.BooleanField(required=False, initial=False)
243     all_questions_watched_tags = forms.BooleanField(required=False, initial=False)
244     questions_asked = forms.BooleanField(required=False, initial=False)
245     questions_answered = forms.BooleanField(required=False, initial=False)
246     questions_commented = forms.BooleanField(required=False, initial=False)
247     questions_viewed = forms.BooleanField(required=False, initial=False)
248
249     notify_answers = forms.BooleanField(required=False, initial=False)
250     notify_reply_to_comments = forms.BooleanField(required=False, initial=False)
251     notify_comments_own_post = forms.BooleanField(required=False, initial=False)
252     notify_comments = forms.BooleanField(required=False, initial=False)
253     notify_accepted = forms.BooleanField(required=False, initial=False)
254