]> git.openstreetmap.org Git - osqa.git/blob - forum/forms.py
Closing http://jira.osqa.net/browse/OSQA-24 with a bonus, it's also possible to speci...
[osqa.git] / forum / forms.py
1 import re
2 from datetime import date
3 from django import forms
4 from models import *
5 from const import *
6 from django.utils.translation import ugettext as _
7 from django.contrib.humanize.templatetags.humanize import apnumber
8 from forum.models import User
9
10 from django.utils.safestring import mark_safe
11 from forum.utils.forms import NextUrlField, UserNameField, SetPasswordForm
12 from django.conf import settings
13 import logging
14
15 class TitleField(forms.CharField):
16     def __init__(self, *args, **kwargs):
17         super(TitleField, self).__init__(*args, **kwargs)
18         self.required = True
19         self.widget = forms.TextInput(attrs={'size' : 70, 'autocomplete' : 'off'})
20         self.max_length = 255
21         self.label  = _('title')
22         self.help_text = _('please enter a descriptive title for your question')
23         self.initial = ''
24
25     def clean(self, value):
26         if len(value) < settings.FORM_MIN_QUESTION_TITLE:
27             raise forms.ValidationError(_('title must be must be at least %s characters' % settings.FORM_MIN_QUESTION_TITLE))
28
29         return value
30
31 class EditorField(forms.CharField):
32     def __init__(self, *args, **kwargs):
33         super(EditorField, self).__init__(*args, **kwargs)
34         self.required = True
35         self.widget = forms.Textarea(attrs={'id':'editor'})
36         self.label  = _('content')
37         self.help_text = u''
38         self.initial = ''
39
40     def clean(self, value):
41         if len(value) < settings.FORM_MIN_QUESTION_BODY and not settings.FORM_EMPTY_QUESTION_BODY:
42             raise forms.ValidationError(_('question content must be must be at least %s characters' % settings.FORM_MIN_QUESTION_BODY))
43
44         return value
45
46 class TagNamesField(forms.CharField):
47     def __init__(self, *args, **kwargs):
48         super(TagNamesField, self).__init__(*args, **kwargs)
49         self.required = True
50         self.widget = forms.TextInput(attrs={'size' : 50, 'autocomplete' : 'off'})
51         self.max_length = 255
52         self.label  = _('tags')
53         #self.help_text = _('please use space to separate tags (this enables autocomplete feature)')
54         self.help_text = _('Tags are short keywords, with no spaces within. At least one %(min)s and up to %(max)s tags can be used.') % {
55             'min': apnumber(settings.FORM_MIN_NUMBER_OF_TAGS), 'max': apnumber(settings.FORM_MAX_NUMBER_OF_TAGS)    
56         }
57         self.initial = ''
58
59     def clean(self, value):
60         value = super(TagNamesField, self).clean(value)
61         data = value.strip()
62         if len(data) < 1:
63             raise forms.ValidationError(_('tags are required'))
64
65         split_re = re.compile(r'[ ,]+')
66         list = split_re.split(data)
67         list_temp = []
68         if len(list) > settings.FORM_MAX_NUMBER_OF_TAGS or len(list) < settings.FORM_MIN_NUMBER_OF_TAGS:
69             raise forms.ValidationError(_('please use betwen %(min)s and %(max)s tags') % {
70             'min': apnumber(settings.FORM_MIN_NUMBER_OF_TAGS), 'max': apnumber(settings.FORM_MAX_NUMBER_OF_TAGS)
71         })
72
73         tagname_re = re.compile(r'[a-z0-9]+')
74         for tag in list:
75             if len(tag) > 20:
76                 raise forms.ValidationError(_('tags must be shorter than 20 characters'))
77             if not tagname_re.match(tag):
78                 raise forms.ValidationError(_('please use following characters in tags: letters \'a-z\', numbers, and characters \'.-_#\''))
79             # only keep one same tag
80             if tag not in list_temp and len(tag.strip()) > 0:
81                 list_temp.append(tag)
82         return u' '.join(list_temp)
83
84 class WikiField(forms.BooleanField):
85     def __init__(self, *args, **kwargs):
86         super(WikiField, self).__init__(*args, **kwargs)
87         self.required = False
88         self.label  = _('community wiki')
89         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')
90     def clean(self,value):
91         return value and settings.WIKI_ON
92
93 class EmailNotifyField(forms.BooleanField):
94     def __init__(self, *args, **kwargs):
95         super(EmailNotifyField, self).__init__(*args, **kwargs)
96         self.required = False
97         self.widget.attrs['class'] = 'nomargin'
98
99 class SummaryField(forms.CharField):
100     def __init__(self, *args, **kwargs):
101         super(SummaryField, self).__init__(*args, **kwargs)
102         self.required = False
103         self.widget = forms.TextInput(attrs={'size' : 50, 'autocomplete' : 'off'})
104         self.max_length = 300
105         self.label  = _('update summary:')
106         self.help_text = _('enter a brief summary of your revision (e.g. fixed spelling, grammar, improved style, this field is optional)')
107
108
109 class FeedbackForm(forms.Form):
110     name = forms.CharField(label=_('Your name:'), required=False)
111     email = forms.EmailField(label=_('Email (not shared with anyone):'), required=False)
112     message = forms.CharField(label=_('Your message:'), max_length=800,widget=forms.Textarea(attrs={'cols':60}))
113     next = NextUrlField()
114
115 class AskForm(forms.Form):
116     title  = TitleField()
117     text   = EditorField()
118     tags   = TagNamesField()
119     wiki = WikiField()
120
121
122 class AnswerForm(forms.Form):
123     text   = EditorField()
124     wiki   = WikiField()
125
126     def __init__(self, question, *args, **kwargs):
127         super(AnswerForm, self).__init__(*args, **kwargs)
128
129         if question.wiki and settings.WIKI_ON:
130             self.fields['wiki'].initial = True
131
132
133 class CloseForm(forms.Form):
134     reason = forms.ChoiceField(choices=CLOSE_REASONS)
135
136 class RetagQuestionForm(forms.Form):
137     tags   = TagNamesField()
138     # initialize the default values
139     def __init__(self, question, *args, **kwargs):
140         super(RetagQuestionForm, self).__init__(*args, **kwargs)
141         self.fields['tags'].initial = question.tagnames
142
143 class RevisionForm(forms.Form):
144     """
145     Lists revisions of a Question or Answer
146     """
147     revision = forms.ChoiceField(widget=forms.Select(attrs={'style' : 'width:520px'}))
148
149     def __init__(self, post, *args, **kwargs):
150         super(RevisionForm, self).__init__(*args, **kwargs)
151
152         revisions = post.revisions.all().values_list(
153             'revision', 'author__username', 'revised_at', 'summary')
154         date_format = '%c'
155         self.fields['revision'].choices = [
156             (r[0], u'%s - %s (%s) %s' % (r[0], r[1], r[2].strftime(date_format), r[3]))
157             for r in revisions]
158
159         self.fields['revision'].initial = post.active_revision.revision
160
161 class EditQuestionForm(forms.Form):
162     title  = TitleField()
163     text   = EditorField()
164     tags   = TagNamesField()
165     summary = SummaryField()
166
167     def __init__(self, question, revision=None, *args, **kwargs):
168         super(EditQuestionForm, self).__init__(*args, **kwargs)
169
170         if revision is None:
171             revision = question.active_revision
172
173         self.fields['title'].initial = revision.title
174         self.fields['text'].initial = revision.body
175         self.fields['tags'].initial = revision.tagnames
176             
177         # Once wiki mode is enabled, it can't be disabled
178         if not question.wiki:
179             self.fields['wiki'] = WikiField()
180
181 class EditAnswerForm(forms.Form):
182     text = EditorField()
183     summary = SummaryField()
184
185     def __init__(self, answer, revision=None, *args, **kwargs):
186         super(EditAnswerForm, self).__init__(*args, **kwargs)
187
188         if revision is None:
189             revision = answer.active_revision
190
191         self.fields['text'].initial = revision.body
192
193 class EditUserForm(forms.Form):
194     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}))
195     if settings.EDITABLE_SCREEN_NAME:
196         username = UserNameField(label=_('Screen name'))
197     realname = forms.CharField(label=_('Real name'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
198     website = forms.URLField(label=_('Website'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
199     city = forms.CharField(label=_('Location'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
200     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}))
201     about = forms.CharField(label=_('Profile'), required=False, widget=forms.Textarea(attrs={'cols' : 60}))
202
203     def __init__(self, user, *args, **kwargs):
204         super(EditUserForm, self).__init__(*args, **kwargs)
205         logging.debug('initializing the form')
206         if settings.EDITABLE_SCREEN_NAME:
207             self.fields['username'].initial = user.username
208             self.fields['username'].user_instance = user
209         self.fields['email'].initial = user.email
210         self.fields['realname'].initial = user.real_name
211         self.fields['website'].initial = user.website
212         self.fields['city'].initial = user.location
213
214         if user.date_of_birth is not None:
215             self.fields['birthday'].initial = user.date_of_birth
216         else:
217             self.fields['birthday'].initial = '1990-01-01'
218         self.fields['about'].initial = user.about
219         self.user = user
220
221     def clean_email(self):
222         """For security reason one unique email in database"""
223         if self.user.email != self.cleaned_data['email']:
224             #todo dry it, there is a similar thing in openidauth
225             if settings.EMAIL_UNIQUE == True:
226                 if 'email' in self.cleaned_data:
227                     try:
228                         user = User.objects.get(email = self.cleaned_data['email'])
229                     except User.DoesNotExist:
230                         return self.cleaned_data['email']
231                     except User.MultipleObjectsReturned:
232                         raise forms.ValidationError(_('this email has already been registered, please use another one'))
233                     raise forms.ValidationError(_('this email has already been registered, please use another one'))
234         return self.cleaned_data['email']
235
236
237 class SubscriptionSettingsForm(forms.Form):
238     member_joins = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
239     new_question = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
240     new_question_watched_tags = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
241     subscribed_questions = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
242
243     all_questions = forms.BooleanField(required=False, initial=False)
244     all_questions_watched_tags = forms.BooleanField(required=False, initial=False)
245     questions_asked = forms.BooleanField(required=False, initial=False)
246     questions_answered = forms.BooleanField(required=False, initial=False)
247     questions_commented = forms.BooleanField(required=False, initial=False)
248     questions_viewed = forms.BooleanField(required=False, initial=False)
249
250     notify_answers = forms.BooleanField(required=False, initial=False)
251     notify_reply_to_comments = forms.BooleanField(required=False, initial=False)
252     notify_comments_own_post = forms.BooleanField(required=False, initial=False)
253     notify_comments = forms.BooleanField(required=False, initial=False)
254     notify_accepted = forms.BooleanField(required=False, initial=False)
255