]> git.openstreetmap.org Git - osqa.git/blob - forum/forms.py
Added the option to limit the tags creation. It will defaults to false, and there...
[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.widget = forms.Textarea(attrs={'id':'editor'})
34         self.label  = _('content')
35         self.help_text = u''
36         self.initial = ''
37
38
39 class QuestionEditorField(EditorField):
40     def __init__(self, *args, **kwargs):
41         super(QuestionEditorField, self).__init__(*args, **kwargs)
42         self.required = not bool(settings.FORM_EMPTY_QUESTION_BODY)
43
44
45     def clean(self, value):
46         if self.required and (len(value) < settings.FORM_MIN_QUESTION_BODY):
47             raise forms.ValidationError(_('question content must be at least %s characters') % settings.FORM_MIN_QUESTION_BODY)
48
49         return value
50
51 class AnswerEditorField(EditorField):
52     def __init__(self, *args, **kwargs):
53         super(AnswerEditorField, self).__init__(*args, **kwargs)
54         self.required = True
55
56     def clean(self, value):
57         if len(value) < settings.FORM_MIN_QUESTION_BODY:
58             raise forms.ValidationError(_('answer content must be at least %s characters') % settings.FORM_MIN_QUESTION_BODY)
59
60         return value
61
62
63 class TagNamesField(forms.CharField):
64     def __init__(self, user=None, *args, **kwargs):
65         super(TagNamesField, self).__init__(*args, **kwargs)
66         self.required = True
67         self.widget = forms.TextInput(attrs={'size' : 50, 'autocomplete' : 'off'})
68         self.max_length = 255
69         self.label  = _('tags')
70         #self.help_text = _('please use space to separate tags (this enables autocomplete feature)')
71         self.help_text = _('Tags are short keywords, with no spaces within. At least %(min)s and up to %(max)s tags can be used.') % {
72             'min': settings.FORM_MIN_NUMBER_OF_TAGS, 'max': settings.FORM_MAX_NUMBER_OF_TAGS    
73         }
74         self.initial = ''
75         self.user = user
76
77     def clean(self, value):
78         value = super(TagNamesField, self).clean(value)
79         data = value.strip().lower()
80
81         split_re = re.compile(r'[ ,]+')
82         list = split_re.split(data)
83
84         if len(list) > settings.FORM_MAX_NUMBER_OF_TAGS or len(list) < settings.FORM_MIN_NUMBER_OF_TAGS:
85             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})
86
87         list_temp = []
88         tagname_re = re.compile(r'^[\w+\.-]+$', re.UNICODE)
89         for tag in list:
90             if len(tag) > settings.FORM_MAX_LENGTH_OF_TAG or len(tag) < settings.FORM_MIN_LENGTH_OF_TAG:
91                 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})
92             if not tagname_re.match(tag):
93                 raise forms.ValidationError(_('please use following characters in tags: letters , numbers, and characters \'.-_\''))
94             # only keep one same tag
95             if tag not in list_temp and len(tag.strip()) > 0:
96                 list_temp.append(tag)
97
98         if settings.LIMIT_TAG_CREATION and not self.user.can_create_tags():
99             existent = Tag.objects.filter(name__in=list_temp).values_list('name', flat=True)
100
101             if len(existent) < len(list_temp):
102                 unexistent = [n for n in list_temp if not n in existent]
103                 raise forms.ValidationError(_("You don't have enough reputation to create new tags. The following tags do not exist yet: %s") %
104                         ', '.join(unexistent))
105
106
107         return u' '.join(list_temp)
108
109 class WikiField(forms.BooleanField):
110     def __init__(self, disabled=False, *args, **kwargs):
111         super(WikiField, self).__init__(*args, **kwargs)
112         self.required = False
113         self.label  = _('community wiki')
114         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')
115         if disabled:
116             self.widget=forms.CheckboxInput(attrs={'disabled': "disabled"})
117     def clean(self,value):
118         return value
119
120 class EmailNotifyField(forms.BooleanField):
121     def __init__(self, *args, **kwargs):
122         super(EmailNotifyField, self).__init__(*args, **kwargs)
123         self.required = False
124         self.widget.attrs['class'] = 'nomargin'
125
126 class SummaryField(forms.CharField):
127     def __init__(self, *args, **kwargs):
128         super(SummaryField, self).__init__(*args, **kwargs)
129         self.required = False
130         self.widget = forms.TextInput(attrs={'size' : 50, 'autocomplete' : 'off'})
131         self.max_length = 300
132         self.label  = _('update summary:')
133         self.help_text = _('enter a brief summary of your revision (e.g. fixed spelling, grammar, improved style, this field is optional)')
134
135
136 class FeedbackForm(forms.Form):
137     name = forms.CharField(label=_('Your name:'), required=False)
138     email = forms.EmailField(label=_('Email (not shared with anyone):'), required=False)
139     message = forms.CharField(label=_('Your message:'), max_length=800,widget=forms.Textarea(attrs={'cols':60}))
140     next = NextUrlField()
141
142 class AskForm(forms.Form):
143     title  = TitleField()
144     text   = QuestionEditorField()
145
146     def __init__(self, data=None, user=None, *args, **kwargs):
147         super(AskForm, self).__init__(data, *args, **kwargs)
148
149         self.fields['tags']   = TagNamesField(user)
150
151         if settings.WIKI_ON:
152             self.fields['wiki'] = WikiField()
153
154 class AnswerForm(forms.Form):
155     text   = AnswerEditorField()
156     wiki   = WikiField()
157
158     def __init__(self, question, *args, **kwargs):
159         super(AnswerForm, self).__init__(*args, **kwargs)
160
161         if settings.WIKI_ON:
162             self.fields['wiki'] = WikiField()
163
164             if question.nis.wiki:
165                 self.fields['wiki'].initial = True
166
167
168 class RetagQuestionForm(forms.Form):
169     tags   = TagNamesField()
170     # initialize the default values
171     def __init__(self, question, *args, **kwargs):
172         super(RetagQuestionForm, self).__init__(*args, **kwargs)
173         self.fields['tags'].initial = question.tagnames
174
175 class RevisionForm(forms.Form):
176     """
177     Lists revisions of a Question or Answer
178     """
179     revision = forms.ChoiceField(widget=forms.Select(attrs={'style' : 'width:520px'}))
180
181     def __init__(self, post, *args, **kwargs):
182         super(RevisionForm, self).__init__(*args, **kwargs)
183
184         revisions = post.revisions.all().values_list(
185             'revision', 'author__username', 'revised_at', 'summary')
186         date_format = '%c'
187         self.fields['revision'].choices = [
188             (r[0], u'%s - %s (%s) %s' % (r[0], r[1], r[2].strftime(date_format), r[3]))
189             for r in revisions]
190
191         self.fields['revision'].initial = post.active_revision.revision
192
193 class EditQuestionForm(forms.Form):
194     title  = TitleField()
195     text   = QuestionEditorField()
196     summary = SummaryField()
197
198     def __init__(self, question, user, revision=None, *args, **kwargs):
199         super(EditQuestionForm, self).__init__(*args, **kwargs)
200
201         if revision is None:
202             revision = question.active_revision
203
204         self.fields['title'].initial = revision.title
205         self.fields['text'].initial = revision.body
206
207         self.fields['tags'] = TagNamesField(user)
208         self.fields['tags'].initial = revision.tagnames
209
210         if settings.WIKI_ON:
211             self.fields['wiki'] = WikiField(disabled=(question.nis.wiki and not user.can_cancel_wiki(question)), initial=question.nis.wiki)
212
213 class EditAnswerForm(forms.Form):
214     text = AnswerEditorField()
215     summary = SummaryField()
216
217     def __init__(self, answer, user, revision=None, *args, **kwargs):
218         super(EditAnswerForm, self).__init__(*args, **kwargs)
219
220         if revision is None:
221             revision = answer.active_revision
222
223         self.fields['text'].initial = revision.body
224
225         if settings.WIKI_ON:
226             self.fields['wiki'] = WikiField(disabled=(answer.nis.wiki and not user.can_cancel_wiki(answer)), initial=answer.nis.wiki)
227
228 class EditUserForm(forms.Form):
229     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}))
230     realname = forms.CharField(label=_('Real name'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
231     website = forms.URLField(label=_('Website'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
232     city = forms.CharField(label=_('Location'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
233     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}))
234     about = forms.CharField(label=_('Profile'), required=False, widget=forms.Textarea(attrs={'cols' : 60}))
235
236     def __init__(self, user, *args, **kwargs):
237         super(EditUserForm, self).__init__(*args, **kwargs)
238         if settings.EDITABLE_SCREEN_NAME:
239             self.fields['username'] = UserNameField(label=_('Screen name'))
240             self.fields['username'].initial = user.username
241             self.fields['username'].user_instance = user
242         self.fields['email'].initial = user.email
243         self.fields['realname'].initial = user.real_name
244         self.fields['website'].initial = user.website
245         self.fields['city'].initial = user.location
246
247         if user.date_of_birth is not None:
248             self.fields['birthday'].initial = user.date_of_birth
249         else:
250             self.fields['birthday'].initial = '1990-01-01'
251         self.fields['about'].initial = user.about
252         self.user = user
253
254     def clean_email(self):
255         """For security reason one unique email in database"""
256         if self.user.email != self.cleaned_data['email']:
257             #todo dry it, there is a similar thing in openidauth
258             if settings.EMAIL_UNIQUE == True:
259                 if 'email' in self.cleaned_data:
260                     try:
261                         user = User.objects.get(email = self.cleaned_data['email'])
262                     except User.DoesNotExist:
263                         return self.cleaned_data['email']
264                     except User.MultipleObjectsReturned:
265                         raise forms.ValidationError(_('this email has already been registered, please use another one'))
266                     raise forms.ValidationError(_('this email has already been registered, please use another one'))
267         return self.cleaned_data['email']
268
269 NOTIFICATION_CHOICES = (
270     ('i', _('Instantly')),
271     ('d', _('Daily')),
272     ('w', _('Weekly')),
273     ('n', _('No notifications')),
274 )
275
276 class SubscriptionSettingsForm(forms.Form):
277     member_joins = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
278     new_question = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
279     new_question_watched_tags = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
280     subscribed_questions = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
281
282     all_questions = forms.BooleanField(required=False, initial=False)
283     all_questions_watched_tags = forms.BooleanField(required=False, initial=False)
284     questions_asked = forms.BooleanField(required=False, initial=False)
285     questions_answered = forms.BooleanField(required=False, initial=False)
286     questions_commented = forms.BooleanField(required=False, initial=False)
287     questions_viewed = forms.BooleanField(required=False, initial=False)
288
289     notify_answers = forms.BooleanField(required=False, initial=False)
290     notify_reply_to_comments = forms.BooleanField(required=False, initial=False)
291     notify_comments_own_post = forms.BooleanField(required=False, initial=False)
292     notify_comments = forms.BooleanField(required=False, initial=False)
293     notify_accepted = forms.BooleanField(required=False, initial=False)
294