]> git.openstreetmap.org Git - osqa.git/blob - forum/forms.py
Some improvements in cache.
[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 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 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, *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
76     def clean(self, value):
77         value = super(TagNamesField, self).clean(value)
78         data = value.strip().lower()
79
80         split_re = re.compile(r'[ ,]+')
81         list = split_re.split(data)
82
83         if len(list) > settings.FORM_MAX_NUMBER_OF_TAGS or len(list) < settings.FORM_MIN_NUMBER_OF_TAGS:
84             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})
85
86         list_temp = []
87         tagname_re = re.compile(r'^[\w+\.-]+$', re.UNICODE)
88         for tag in list:
89             if len(tag) > settings.FORM_MAX_LENGTH_OF_TAG or len(tag) < settings.FORM_MIN_LENGTH_OF_TAG:
90                 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})
91             if not tagname_re.match(tag):
92                 raise forms.ValidationError(_('please use following characters in tags: letters , numbers, and characters \'.-_\''))
93             # only keep one same tag
94             if tag not in list_temp and len(tag.strip()) > 0:
95                 list_temp.append(tag)
96
97         return u' '.join(list_temp)
98
99 class WikiField(forms.BooleanField):
100     def __init__(self, *args, **kwargs):
101         super(WikiField, self).__init__(*args, **kwargs)
102         self.required = False
103         self.label  = _('community wiki')
104         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')
105     def clean(self,value):
106         return value and settings.WIKI_ON
107
108 class EmailNotifyField(forms.BooleanField):
109     def __init__(self, *args, **kwargs):
110         super(EmailNotifyField, self).__init__(*args, **kwargs)
111         self.required = False
112         self.widget.attrs['class'] = 'nomargin'
113
114 class SummaryField(forms.CharField):
115     def __init__(self, *args, **kwargs):
116         super(SummaryField, self).__init__(*args, **kwargs)
117         self.required = False
118         self.widget = forms.TextInput(attrs={'size' : 50, 'autocomplete' : 'off'})
119         self.max_length = 300
120         self.label  = _('update summary:')
121         self.help_text = _('enter a brief summary of your revision (e.g. fixed spelling, grammar, improved style, this field is optional)')
122
123
124 class FeedbackForm(forms.Form):
125     name = forms.CharField(label=_('Your name:'), required=False)
126     email = forms.EmailField(label=_('Email (not shared with anyone):'), required=False)
127     message = forms.CharField(label=_('Your message:'), max_length=800,widget=forms.Textarea(attrs={'cols':60}))
128     next = NextUrlField()
129
130 class AskForm(forms.Form):
131     title  = TitleField()
132     text   = QuestionEditorField()
133     tags   = TagNamesField()
134     wiki = WikiField()
135
136
137 class AnswerForm(forms.Form):
138     text   = AnswerEditorField()
139     wiki   = WikiField()
140
141     def __init__(self, question, *args, **kwargs):
142         super(AnswerForm, self).__init__(*args, **kwargs)
143
144         if question.wiki and settings.WIKI_ON:
145             self.fields['wiki'].initial = True
146
147
148 class RetagQuestionForm(forms.Form):
149     tags   = TagNamesField()
150     # initialize the default values
151     def __init__(self, question, *args, **kwargs):
152         super(RetagQuestionForm, self).__init__(*args, **kwargs)
153         self.fields['tags'].initial = question.tagnames
154
155 class RevisionForm(forms.Form):
156     """
157     Lists revisions of a Question or Answer
158     """
159     revision = forms.ChoiceField(widget=forms.Select(attrs={'style' : 'width:520px'}))
160
161     def __init__(self, post, *args, **kwargs):
162         super(RevisionForm, self).__init__(*args, **kwargs)
163
164         revisions = post.revisions.all().values_list(
165             'revision', 'author__username', 'revised_at', 'summary')
166         date_format = '%c'
167         self.fields['revision'].choices = [
168             (r[0], u'%s - %s (%s) %s' % (r[0], r[1], r[2].strftime(date_format), r[3]))
169             for r in revisions]
170
171         self.fields['revision'].initial = post.active_revision.revision
172
173 class EditQuestionForm(forms.Form):
174     title  = TitleField()
175     text   = QuestionEditorField()
176     tags   = TagNamesField()
177     summary = SummaryField()
178
179     def __init__(self, question, revision=None, *args, **kwargs):
180         super(EditQuestionForm, self).__init__(*args, **kwargs)
181
182         if revision is None:
183             revision = question.active_revision
184
185         self.fields['title'].initial = revision.title
186         self.fields['text'].initial = revision.body
187         self.fields['tags'].initial = revision.tagnames
188             
189         # Once wiki mode is enabled, it can't be disabled
190         if not question.wiki:
191             self.fields['wiki'] = WikiField()
192
193 class EditAnswerForm(forms.Form):
194     text = AnswerEditorField()
195     summary = SummaryField()
196
197     def __init__(self, answer, revision=None, *args, **kwargs):
198         super(EditAnswerForm, self).__init__(*args, **kwargs)
199
200         if revision is None:
201             revision = answer.active_revision
202
203         self.fields['text'].initial = revision.body
204
205 class EditUserForm(forms.Form):
206     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}))
207     realname = forms.CharField(label=_('Real name'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
208     website = forms.URLField(label=_('Website'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
209     city = forms.CharField(label=_('Location'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
210     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}))
211     about = forms.CharField(label=_('Profile'), required=False, widget=forms.Textarea(attrs={'cols' : 60}))
212
213     def __init__(self, user, *args, **kwargs):
214         super(EditUserForm, self).__init__(*args, **kwargs)
215         if settings.EDITABLE_SCREEN_NAME:
216             self.fields['username'] = UserNameField(label=_('Screen name'))
217             self.fields['username'].initial = user.username
218             self.fields['username'].user_instance = user
219         self.fields['email'].initial = user.email
220         self.fields['realname'].initial = user.real_name
221         self.fields['website'].initial = user.website
222         self.fields['city'].initial = user.location
223
224         if user.date_of_birth is not None:
225             self.fields['birthday'].initial = user.date_of_birth
226         else:
227             self.fields['birthday'].initial = '1990-01-01'
228         self.fields['about'].initial = user.about
229         self.user = user
230
231     def clean_email(self):
232         """For security reason one unique email in database"""
233         if self.user.email != self.cleaned_data['email']:
234             #todo dry it, there is a similar thing in openidauth
235             if settings.EMAIL_UNIQUE == True:
236                 if 'email' in self.cleaned_data:
237                     try:
238                         user = User.objects.get(email = self.cleaned_data['email'])
239                     except User.DoesNotExist:
240                         return self.cleaned_data['email']
241                     except User.MultipleObjectsReturned:
242                         raise forms.ValidationError(_('this email has already been registered, please use another one'))
243                     raise forms.ValidationError(_('this email has already been registered, please use another one'))
244         return self.cleaned_data['email']
245
246 NOTIFICATION_CHOICES = (
247     ('i', _('Instantly')),
248     ('d', _('Daily')),
249     ('w', _('Weekly')),
250     ('n', _('No notifications')),
251 )
252
253 class SubscriptionSettingsForm(forms.Form):
254     member_joins = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
255     new_question = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
256     new_question_watched_tags = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
257     subscribed_questions = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
258
259     all_questions = forms.BooleanField(required=False, initial=False)
260     all_questions_watched_tags = forms.BooleanField(required=False, initial=False)
261     questions_asked = forms.BooleanField(required=False, initial=False)
262     questions_answered = forms.BooleanField(required=False, initial=False)
263     questions_commented = forms.BooleanField(required=False, initial=False)
264     questions_viewed = forms.BooleanField(required=False, initial=False)
265
266     notify_answers = forms.BooleanField(required=False, initial=False)
267     notify_reply_to_comments = forms.BooleanField(required=False, initial=False)
268     notify_comments_own_post = forms.BooleanField(required=False, initial=False)
269     notify_comments = forms.BooleanField(required=False, initial=False)
270     notify_accepted = forms.BooleanField(required=False, initial=False)
271