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