]> git.openstreetmap.org Git - osqa.git/blob - forum/forms/qanda.py
Merge pull request #40 from jasimmk/master
[osqa.git] / forum / forms / qanda.py
1 import re
2 from datetime import date
3 from django import forms
4 from forum.models import *
5 from django.utils.translation import ugettext as _
6
7 from django.utils.encoding import smart_unicode
8 from general import NextUrlField, UserNameField
9
10 from forum import settings, REQUEST_HOLDER
11
12 from forum.modules import call_all_handlers
13
14 import logging
15
16 class TitleField(forms.CharField):
17     def __init__(self, *args, **kwargs):
18         super(TitleField, self).__init__(*args, **kwargs)
19
20         self.required = True
21         self.max_length = 255
22         self.widget = forms.TextInput(attrs={'size' : 70, 'autocomplete' : 'off', 'maxlength' : self.max_length})
23         self.label  = _('title')
24         self.help_text = _('please enter a descriptive title for your question')
25         self.initial = ''
26
27     def clean(self, value):
28         super(TitleField, self).clean(value)
29
30         if len(value) < settings.FORM_MIN_QUESTION_TITLE:
31             raise forms.ValidationError(_('title must be must be at least %s characters') % settings.FORM_MIN_QUESTION_TITLE)
32
33         return value
34
35 class EditorField(forms.CharField):
36     def __init__(self, *args, **kwargs):
37         super(EditorField, self).__init__(*args, **kwargs)
38
39         self.widget = forms.Textarea(attrs={'id':'editor'})
40         self.label  = _('content')
41         self.help_text = u''
42         self.initial = ''
43
44
45 class QuestionEditorField(EditorField):
46     def __init__(self, *args, **kwargs):
47         super(QuestionEditorField, self).__init__(*args, **kwargs)
48         self.required = not bool(settings.FORM_EMPTY_QUESTION_BODY)
49
50
51     def clean(self, value):
52         super(QuestionEditorField, self).clean(value)
53
54         if not bool(settings.FORM_EMPTY_QUESTION_BODY) and (len(re.sub('[ ]{2,}', ' ', value)) < settings.FORM_MIN_QUESTION_BODY):
55             raise forms.ValidationError(_('question content must be at least %s characters') % settings.FORM_MIN_QUESTION_BODY)
56
57         return value
58
59 class AnswerEditorField(EditorField):
60     def __init__(self, *args, **kwargs):
61         super(AnswerEditorField, self).__init__(*args, **kwargs)
62         self.required = True
63
64     def clean(self, value):
65         super(AnswerEditorField, self).clean(value)
66
67         if len(re.sub('[ ]{2,}', ' ', value)) < settings.FORM_MIN_QUESTION_BODY:
68             raise forms.ValidationError(_('answer content must be at least %s characters') % settings.FORM_MIN_QUESTION_BODY)
69
70         return value
71
72
73 class TagNamesField(forms.CharField):
74     def __init__(self, user=None, *args, **kwargs):
75         super(TagNamesField, self).__init__(*args, **kwargs)
76
77         self.required = True
78         self.widget = forms.TextInput(attrs={'size' : 50, 'autocomplete' : 'off'})
79         self.max_length = 255
80         self.label  = _('tags')
81         #self.help_text = _('please use space to separate tags (this enables autocomplete feature)')
82         self.help_text = _('Tags are short keywords, with no spaces within. At least %(min)s and up to %(max)s tags can be used.') % {
83             'min': settings.FORM_MIN_NUMBER_OF_TAGS, 'max': settings.FORM_MAX_NUMBER_OF_TAGS    
84         }
85         self.initial = ''
86         self.user = user
87
88     def clean(self, value):
89         super(TagNamesField, self).clean(value)
90
91         value = super(TagNamesField, self).clean(value)
92         data = value.strip().lower()
93
94         split_re = re.compile(r'[ ,]+')
95         list = {}
96         for tag in split_re.split(data):
97             list[tag] = tag
98
99         if len(list) > settings.FORM_MAX_NUMBER_OF_TAGS or len(list) < settings.FORM_MIN_NUMBER_OF_TAGS:
100             raise forms.ValidationError(_('please use between %(min)s and %(max)s tags') % { 'min': settings.FORM_MIN_NUMBER_OF_TAGS, 'max': settings.FORM_MAX_NUMBER_OF_TAGS})
101
102         list_temp = []
103         tagname_re = re.compile(r'^[\w+#\.-]+$', re.UNICODE)
104         for key,tag in list.items():
105             if len(tag) > settings.FORM_MAX_LENGTH_OF_TAG or len(tag) < settings.FORM_MIN_LENGTH_OF_TAG:
106                 raise forms.ValidationError(_('please use between %(min)s and %(max)s characters in you tags') % { 'min': settings.FORM_MIN_LENGTH_OF_TAG, 'max': settings.FORM_MAX_LENGTH_OF_TAG})
107             if not tagname_re.match(tag):
108                 raise forms.ValidationError(_('please use following characters in tags: letters , numbers, and characters \'.#-_\''))
109             # only keep one same tag
110             if tag not in list_temp and len(tag.strip()) > 0:
111                 list_temp.append(tag)
112
113         if settings.LIMIT_TAG_CREATION and not self.user.can_create_tags():
114             existent = Tag.objects.filter(name__in=list_temp).values_list('name', flat=True)
115
116             if len(existent) < len(list_temp):
117                 unexistent = [n for n in list_temp if not n in existent]
118                 raise forms.ValidationError(_("You don't have enough reputation to create new tags. The following tags do not exist yet: %s") %
119                         ', '.join(unexistent))
120
121
122         return u' '.join(list_temp)
123
124 class WikiField(forms.BooleanField):
125     def __init__(self, disabled=False, *args, **kwargs):
126         super(WikiField, self).__init__(*args, **kwargs)
127         self.required = False
128         self.label  = _('community wiki')
129         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')
130         if disabled:
131             self.widget=forms.CheckboxInput(attrs={'disabled': "disabled"})
132     def clean(self,value):
133         return value
134
135 class EmailNotifyField(forms.BooleanField):
136     def __init__(self, *args, **kwargs):
137         super(EmailNotifyField, self).__init__(*args, **kwargs)
138         self.required = False
139         self.widget.attrs['class'] = 'nomargin'
140
141 class SummaryField(forms.CharField):
142     def __init__(self, *args, **kwargs):
143         super(SummaryField, self).__init__(*args, **kwargs)
144         self.required = False
145         self.widget = forms.TextInput(attrs={'size' : 50, 'autocomplete' : 'off'})
146         self.max_length = 300
147         self.label  = _('update summary:')
148         self.help_text = _('enter a brief summary of your revision (e.g. fixed spelling, grammar, improved style, this field is optional)')
149
150
151 class FeedbackForm(forms.Form):
152     message = forms.CharField(label=_('Your message:'), max_length=800,widget=forms.Textarea(attrs={'cols':60}))
153     next = NextUrlField()
154
155     def __init__(self, user, *args, **kwargs):
156         super(FeedbackForm, self).__init__(*args, **kwargs)
157         if not user.is_authenticated():
158             self.fields['name'] = forms.CharField(label=_('Your name:'), required=False)
159             self.fields['email'] = forms.EmailField(label=_('Email (not shared with anyone):'), required=True)
160
161         # Create anti spam fields
162         spam_fields = call_all_handlers('create_anti_spam_field')
163         if spam_fields:
164             spam_fields = dict(spam_fields)
165             for name, field in spam_fields.items():
166                 self.fields[name] = field
167
168             self._anti_spam_fields = spam_fields.keys()
169         else:
170             self._anti_spam_fields = []
171
172
173
174 class AskForm(forms.Form):
175     title  = TitleField()
176     text   = QuestionEditorField()
177
178     def __init__(self, data=None, user=None, *args, **kwargs):
179         super(AskForm, self).__init__(data, *args, **kwargs)
180
181         self.fields['tags']   = TagNamesField(user)
182         
183         if not user.is_authenticated() or (int(user.reputation) < settings.CAPTCHA_IF_REP_LESS_THAN and not (user.is_superuser or user.is_staff)):
184             spam_fields = call_all_handlers('create_anti_spam_field')
185             if spam_fields:
186                 spam_fields = dict(spam_fields)
187                 for name, field in spam_fields.items():
188                     self.fields[name] = field
189
190                 self._anti_spam_fields = spam_fields.keys()
191             else:
192                 self._anti_spam_fields = []
193
194         if settings.WIKI_ON:
195             self.fields['wiki'] = WikiField()
196
197 class AnswerForm(forms.Form):
198     text   = AnswerEditorField()
199     wiki   = WikiField()
200
201     def __init__(self, data=None, user=None, *args, **kwargs):
202         super(AnswerForm, self).__init__(data, *args, **kwargs)
203         
204         if not user.is_authenticated() or (int(user.reputation) < settings.CAPTCHA_IF_REP_LESS_THAN and not (user.is_superuser or user.is_staff)):
205             spam_fields = call_all_handlers('create_anti_spam_field')
206             if spam_fields:
207                 spam_fields = dict(spam_fields)
208                 for name, field in spam_fields.items():
209                     self.fields[name] = field
210
211                 self._anti_spam_fields = spam_fields.keys()
212             else:
213                 self._anti_spam_fields = []
214
215         if settings.WIKI_ON:
216             self.fields['wiki'] = WikiField()
217
218 class RetagQuestionForm(forms.Form):
219     tags   = TagNamesField()
220     # initialize the default values
221     def __init__(self, question, *args, **kwargs):
222         super(RetagQuestionForm, self).__init__(*args, **kwargs)
223         self.fields['tags'].initial = question.tagnames
224
225 class RevisionForm(forms.Form):
226     """
227     Lists revisions of a Question or Answer
228     """
229     revision = forms.ChoiceField(widget=forms.Select(attrs={'style' : 'width:520px'}))
230
231     def __init__(self, post, *args, **kwargs):
232         super(RevisionForm, self).__init__(*args, **kwargs)
233
234         revisions = post.revisions.all().values_list('revision', 'author__username', 'revised_at', 'summary').order_by('-revised_at')
235
236         date_format = '%c'
237         self.fields['revision'].choices = [
238             (r[0], u'%s - %s (%s) %s' % (r[0], smart_unicode(r[1]), r[2].strftime(date_format), r[3]))
239             for r in revisions]
240
241         self.fields['revision'].initial = post.active_revision.revision
242
243 class EditQuestionForm(forms.Form):
244     title  = TitleField()
245     text   = QuestionEditorField()
246     summary = SummaryField()
247
248     def __init__(self, question, user, revision=None, *args, **kwargs):
249         super(EditQuestionForm, self).__init__(*args, **kwargs)
250
251         if revision is None:
252             revision = question.active_revision
253
254         self.fields['title'].initial = revision.title
255         self.fields['text'].initial = revision.body
256
257         self.fields['tags'] = TagNamesField(user)
258         self.fields['tags'].initial = revision.tagnames
259
260         if not user.is_authenticated() or (int(user.reputation) < settings.CAPTCHA_IF_REP_LESS_THAN and not (user.is_superuser or user.is_staff)):
261             spam_fields = call_all_handlers('create_anti_spam_field')
262             if spam_fields:
263                 spam_fields = dict(spam_fields)
264                 for name, field in spam_fields.items():
265                     self.fields[name] = field
266
267                 self._anti_spam_fields = spam_fields.keys()
268             else:
269                 self._anti_spam_fields = []
270
271         if settings.WIKI_ON:
272             self.fields['wiki'] = WikiField(disabled=(question.nis.wiki and not user.can_cancel_wiki(question)), initial=question.nis.wiki)
273
274 class EditAnswerForm(forms.Form):
275     text = AnswerEditorField()
276     summary = SummaryField()
277
278     def __init__(self, answer, user, revision=None, *args, **kwargs):
279         super(EditAnswerForm, self).__init__(*args, **kwargs)
280
281         if revision is None:
282             revision = answer.active_revision
283
284         self.fields['text'].initial = revision.body
285
286         if not user.is_authenticated() or (int(user.reputation) < settings.CAPTCHA_IF_REP_LESS_THAN and not (user.is_superuser or user.is_staff)):
287             spam_fields = call_all_handlers('create_anti_spam_field')
288             if spam_fields:
289                 spam_fields = dict(spam_fields)
290                 for name, field in spam_fields.items():
291                     self.fields[name] = field
292
293                 self._anti_spam_fields = spam_fields.keys()
294             else:
295                 self._anti_spam_fields = []
296         
297         if settings.WIKI_ON:
298             self.fields['wiki'] = WikiField(disabled=(answer.nis.wiki and not user.can_cancel_wiki(answer)), initial=answer.nis.wiki)
299
300 class EditUserForm(forms.Form):
301     email = forms.EmailField(label=u'Email', help_text=_('this email does not have to be linked to gravatar'), required=True, max_length=75, widget=forms.TextInput(attrs={'size' : 35}))
302     realname = forms.CharField(label=_('Real name'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
303     website = forms.URLField(label=_('Website'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
304     city = forms.CharField(label=_('Location'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
305     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}))
306     about = forms.CharField(label=_('Profile'), required=False, widget=forms.Textarea(attrs={'cols' : 60}))
307
308     def __init__(self, user, *args, **kwargs):
309         super(EditUserForm, self).__init__(*args, **kwargs)
310         if settings.EDITABLE_SCREEN_NAME or (REQUEST_HOLDER.request.user.is_authenticated() and REQUEST_HOLDER.request.user.is_superuser):
311             self.fields['username'] = UserNameField(label=_('Screen name'))
312             self.fields['username'].initial = user.username
313             self.fields['username'].user_instance = user
314         self.fields['email'].initial = user.email
315         self.fields['realname'].initial = user.real_name
316         self.fields['website'].initial = user.website
317         self.fields['city'].initial = user.location
318
319         if user.date_of_birth is not None:
320             self.fields['birthday'].initial = user.date_of_birth
321
322         self.fields['about'].initial = user.about
323         self.user = user
324
325     def clean_email(self):
326         if self.user.email != self.cleaned_data['email']:
327             if settings.EMAIL_UNIQUE:
328                 if 'email' in self.cleaned_data:
329                     from forum.models import User
330                     try:
331                         User.objects.get(email = self.cleaned_data['email'])
332                     except User.DoesNotExist:
333                         return self.cleaned_data['email']
334                     except User.MultipleObjectsReturned:
335                         logging.error("Found multiple users sharing the same email: %s" % self.cleaned_data['email'])
336                         
337                     raise forms.ValidationError(_('this email has already been registered, please use another one'))
338         return self.cleaned_data['email']
339         
340
341 NOTIFICATION_CHOICES = (
342     ('i', _('Instantly')),
343     #('d', _('Daily')),
344     #('w', _('Weekly')),
345     ('n', _('No notifications')),
346 )
347
348 class SubscriptionSettingsForm(forms.ModelForm):
349     enable_notifications = forms.BooleanField(widget=forms.HiddenInput, required=False)
350     member_joins = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
351     new_question = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
352     new_question_watched_tags = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
353     subscribed_questions = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
354
355     class Meta:
356         model = SubscriptionSettings
357         fields = ['enable_notifications', 'member_joins', 'new_question', 'new_question_watched_tags', 'subscribed_questions']
358
359 class UserPreferencesForm(forms.Form):
360     sticky_sorts = forms.BooleanField(required=False, initial=False)
361
362
363