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