]> git.openstreetmap.org Git - osqa.git/blob - forum/forms/qanda.py
reverting the changes made in commit #1097 for Jira OSQA-593, it resulted another...
[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
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
162
163 class AskForm(forms.Form):
164     title  = TitleField()
165     text   = QuestionEditorField()
166
167     def __init__(self, data=None, user=None, *args, **kwargs):
168         super(AskForm, self).__init__(data, *args, **kwargs)
169
170         self.fields['tags']   = TagNamesField(user)
171         
172         if int(user.reputation) < settings.CAPTCHA_IF_REP_LESS_THAN and not (user.is_superuser or user.is_staff):
173             spam_fields = call_all_handlers('create_anti_spam_field')
174             if spam_fields:
175                 spam_fields = dict(spam_fields)
176                 for name, field in spam_fields.items():
177                     self.fields[name] = field
178
179                 self._anti_spam_fields = spam_fields.keys()
180             else:
181                 self._anti_spam_fields = []
182
183         if settings.WIKI_ON:
184             self.fields['wiki'] = WikiField()
185
186 class AnswerForm(forms.Form):
187     text   = AnswerEditorField()
188     wiki   = WikiField()
189
190     def __init__(self, data=None, user=None, *args, **kwargs):
191         super(AnswerForm, self).__init__(data, *args, **kwargs)
192         
193         if int(user.reputation) < settings.CAPTCHA_IF_REP_LESS_THAN and not (user.is_superuser or user.is_staff):
194             spam_fields = call_all_handlers('create_anti_spam_field')
195             if spam_fields:
196                 spam_fields = dict(spam_fields)
197                 for name, field in spam_fields.items():
198                     self.fields[name] = field
199
200                 self._anti_spam_fields = spam_fields.keys()
201             else:
202                 self._anti_spam_fields = []
203
204         if settings.WIKI_ON:
205             self.fields['wiki'] = WikiField()
206
207 class RetagQuestionForm(forms.Form):
208     tags   = TagNamesField()
209     # initialize the default values
210     def __init__(self, question, *args, **kwargs):
211         super(RetagQuestionForm, self).__init__(*args, **kwargs)
212         self.fields['tags'].initial = question.tagnames
213
214 class RevisionForm(forms.Form):
215     """
216     Lists revisions of a Question or Answer
217     """
218     revision = forms.ChoiceField(widget=forms.Select(attrs={'style' : 'width:520px'}))
219
220     def __init__(self, post, *args, **kwargs):
221         super(RevisionForm, self).__init__(*args, **kwargs)
222
223         revisions = post.revisions.all().values_list('revision', 'author__username', 'revised_at', 'summary').order_by('-revised_at')
224
225         date_format = '%c'
226         self.fields['revision'].choices = [
227             (r[0], u'%s - %s (%s) %s' % (r[0], smart_unicode(r[1]), r[2].strftime(date_format), r[3]))
228             for r in revisions]
229
230         self.fields['revision'].initial = post.active_revision.revision
231
232 class EditQuestionForm(forms.Form):
233     title  = TitleField()
234     text   = QuestionEditorField()
235     summary = SummaryField()
236
237     def __init__(self, question, user, revision=None, *args, **kwargs):
238         super(EditQuestionForm, self).__init__(*args, **kwargs)
239
240         if revision is None:
241             revision = question.active_revision
242
243         self.fields['title'].initial = revision.title
244         self.fields['text'].initial = revision.body
245
246         self.fields['tags'] = TagNamesField(user)
247         self.fields['tags'].initial = revision.tagnames
248
249         if int(user.reputation) < settings.CAPTCHA_IF_REP_LESS_THAN and not (user.is_superuser or user.is_staff):
250             spam_fields = call_all_handlers('create_anti_spam_field')
251             if spam_fields:
252                 spam_fields = dict(spam_fields)
253                 for name, field in spam_fields.items():
254                     self.fields[name] = field
255
256                 self._anti_spam_fields = spam_fields.keys()
257             else:
258                 self._anti_spam_fields = []
259
260         if settings.WIKI_ON:
261             self.fields['wiki'] = WikiField(disabled=(question.nis.wiki and not user.can_cancel_wiki(question)), initial=question.nis.wiki)
262
263 class EditAnswerForm(forms.Form):
264     text = AnswerEditorField()
265     summary = SummaryField()
266
267     def __init__(self, answer, user, revision=None, *args, **kwargs):
268         super(EditAnswerForm, self).__init__(*args, **kwargs)
269
270         if revision is None:
271             revision = answer.active_revision
272
273         self.fields['text'].initial = revision.body
274
275         if int(user.reputation) < settings.CAPTCHA_IF_REP_LESS_THAN and not (user.is_superuser or user.is_staff):
276             spam_fields = call_all_handlers('create_anti_spam_field')
277             if spam_fields:
278                 spam_fields = dict(spam_fields)
279                 for name, field in spam_fields.items():
280                     self.fields[name] = field
281
282                 self._anti_spam_fields = spam_fields.keys()
283             else:
284                 self._anti_spam_fields = []
285         
286         if settings.WIKI_ON:
287             self.fields['wiki'] = WikiField(disabled=(answer.nis.wiki and not user.can_cancel_wiki(answer)), initial=answer.nis.wiki)
288
289 class EditUserForm(forms.Form):
290     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}))
291     realname = forms.CharField(label=_('Real name'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
292     website = forms.URLField(label=_('Website'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
293     city = forms.CharField(label=_('Location'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
294     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}))
295     about = forms.CharField(label=_('Profile'), required=False, widget=forms.Textarea(attrs={'cols' : 60}))
296
297     def __init__(self, user, *args, **kwargs):
298         super(EditUserForm, self).__init__(*args, **kwargs)
299         if settings.EDITABLE_SCREEN_NAME:
300             self.fields['username'] = UserNameField(label=_('Screen name'))
301             self.fields['username'].initial = user.username
302             self.fields['username'].user_instance = user
303         self.fields['email'].initial = user.email
304         self.fields['realname'].initial = user.real_name
305         self.fields['website'].initial = user.website
306         self.fields['city'].initial = user.location
307
308         if user.date_of_birth is not None:
309             self.fields['birthday'].initial = user.date_of_birth
310
311         self.fields['about'].initial = user.about
312         self.user = user
313
314     def clean_email(self):
315         if self.user.email != self.cleaned_data['email']:
316             if settings.EMAIL_UNIQUE:
317                 if 'email' in self.cleaned_data:
318                     from forum.models import User
319                     try:
320                         User.objects.get(email = self.cleaned_data['email'])
321                     except User.DoesNotExist:
322                         return self.cleaned_data['email']
323                     except User.MultipleObjectsReturned:
324                         logging.error("Found multiple users sharing the same email: %s" % self.cleaned_data['email'])
325                         
326                     raise forms.ValidationError(_('this email has already been registered, please use another one'))
327         return self.cleaned_data['email']
328         
329
330 NOTIFICATION_CHOICES = (
331     ('i', _('Instantly')),
332     #('d', _('Daily')),
333     #('w', _('Weekly')),
334     ('n', _('No notifications')),
335 )
336
337 class SubscriptionSettingsForm(forms.ModelForm):
338     enable_notifications = forms.BooleanField(widget=forms.HiddenInput, required=False)
339     member_joins = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
340     new_question = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
341     new_question_watched_tags = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
342     subscribed_questions = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
343
344     class Meta:
345         model = SubscriptionSettings
346
347 class UserPreferencesForm(forms.Form):
348     sticky_sorts = forms.BooleanField(required=False, initial=False)
349
350
351