]> git.openstreetmap.org Git - osqa.git/blob - forum/forms.py
a78f20702a3841937190cff0f251326b975e2f67
[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 forum.models import User
8 from django.contrib.contenttypes.models import ContentType
9 from django.utils.safestring import mark_safe
10 from forum.utils.forms import NextUrlField, UserNameField, SetPasswordForm
11 from django.conf import settings
12 from django.contrib.contenttypes.models import ContentType
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) < 10:
27             raise forms.ValidationError(_('title must be > 10 characters'))
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) < 10:
42             raise forms.ValidationError(_('question content must be > 10 characters'))
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. Up to five tags can be used.')
55         self.initial = ''
56
57     def clean(self, value):
58         value = super(TagNamesField, self).clean(value)
59         data = value.strip()
60         if len(data) < 1:
61             raise forms.ValidationError(_('tags are required'))
62
63         split_re = re.compile(r'[ ,]+')
64         list = split_re.split(data)
65         list_temp = []
66         if len(list) > 5:
67             raise forms.ValidationError(_('please use 5 tags or less'))
68
69         tagname_re = re.compile(r'[a-z0-9]+')
70         for tag in list:
71             if len(tag) > 20:
72                 raise forms.ValidationError(_('tags must be shorter than 20 characters'))
73             if not tagname_re.match(tag):
74                 raise forms.ValidationError(_('please use following characters in tags: letters \'a-z\', numbers, and characters \'.-_#\''))
75             # only keep one same tag
76             if tag not in list_temp and len(tag.strip()) > 0:
77                 list_temp.append(tag)
78         return u' '.join(list_temp)
79
80 class WikiField(forms.BooleanField):
81     def __init__(self, *args, **kwargs):
82         super(WikiField, self).__init__(*args, **kwargs)
83         self.required = False
84         self.label  = _('community wiki')
85         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')
86     def clean(self,value):
87         return value and settings.WIKI_ON
88
89 class EmailNotifyField(forms.BooleanField):
90     def __init__(self, *args, **kwargs):
91         super(EmailNotifyField, self).__init__(*args, **kwargs)
92         self.required = False
93         self.widget.attrs['class'] = 'nomargin'
94
95 class SummaryField(forms.CharField):
96     def __init__(self, *args, **kwargs):
97         super(SummaryField, self).__init__(*args, **kwargs)
98         self.required = False
99         self.widget = forms.TextInput(attrs={'size' : 50, 'autocomplete' : 'off'})
100         self.max_length = 300
101         self.label  = _('update summary:')
102         self.help_text = _('enter a brief summary of your revision (e.g. fixed spelling, grammar, improved style, this field is optional)')
103
104 class ModerateUserForm(forms.ModelForm):
105     is_approved = forms.BooleanField(label=_("Automatically accept user's contributions for the email updates"),
106                                      required=False)
107
108     def clean_is_approved(self):
109         if 'is_approved' not in self.cleaned_data:
110             self.cleaned_data['is_approved'] = False
111         return self.cleaned_data['is_approved']
112
113     class Meta:
114         model = User
115         fields = ('is_approved',)
116
117 class FeedbackForm(forms.Form):
118     name = forms.CharField(label=_('Your name:'), required=False)
119     email = forms.EmailField(label=_('Email (not shared with anyone):'), required=False)
120     message = forms.CharField(label=_('Your message:'), max_length=800,widget=forms.Textarea(attrs={'cols':60}))
121     next = NextUrlField()
122
123 class AskForm(forms.Form):
124     title  = TitleField()
125     text   = EditorField()
126     tags   = TagNamesField()
127     wiki = WikiField()
128
129     openid = forms.CharField(required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 40, 'class':'openid-input'}))
130     user   = forms.CharField(required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
131     email  = forms.CharField(required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
132
133 class AnswerForm(forms.Form):
134     text   = EditorField()
135     wiki   = WikiField()
136     openid = forms.CharField(required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 40, 'class':'openid-input'}))
137     user   = forms.CharField(required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
138     email  = forms.CharField(required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
139     email_notify = EmailNotifyField()
140     def __init__(self, question, user, *args, **kwargs):
141         super(AnswerForm, self).__init__(*args, **kwargs)
142         self.fields['email_notify'].widget.attrs['id'] = 'question-subscribe-updates';
143         if question.wiki and settings.WIKI_ON:
144             self.fields['wiki'].initial = True
145         if user.is_authenticated():
146             if user in question.followed_by.all():
147                 self.fields['email_notify'].initial = True
148                 return
149         self.fields['email_notify'].initial = False
150
151
152 class CloseForm(forms.Form):
153     reason = forms.ChoiceField(choices=CLOSE_REASONS)
154
155 class RetagQuestionForm(forms.Form):
156     tags   = TagNamesField()
157     # initialize the default values
158     def __init__(self, question, *args, **kwargs):
159         super(RetagQuestionForm, self).__init__(*args, **kwargs)
160         self.fields['tags'].initial = question.tagnames
161
162 class RevisionForm(forms.Form):
163     """
164     Lists revisions of a Question or Answer
165     """
166     revision = forms.ChoiceField(widget=forms.Select(attrs={'style' : 'width:520px'}))
167
168     def __init__(self, post, latest_revision, *args, **kwargs):
169         super(RevisionForm, self).__init__(*args, **kwargs)
170         revisions = post.revisions.all().values_list(
171             'revision', 'author__username', 'revised_at', 'summary')
172         date_format = '%c'
173         self.fields['revision'].choices = [
174             (r[0], u'%s - %s (%s) %s' % (r[0], r[1], r[2].strftime(date_format), r[3]))
175             for r in revisions]
176         self.fields['revision'].initial = latest_revision.revision
177
178 class EditQuestionForm(forms.Form):
179     title  = TitleField()
180     text   = EditorField()
181     tags   = TagNamesField()
182     summary = SummaryField()
183
184     def __init__(self, question, revision, *args, **kwargs):
185         super(EditQuestionForm, self).__init__(*args, **kwargs)
186         self.fields['title'].initial = revision.title
187         self.fields['text'].initial = revision.text
188         self.fields['tags'].initial = revision.tagnames
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 = EditorField()
195     summary = SummaryField()
196
197     def __init__(self, answer, revision, *args, **kwargs):
198         super(EditAnswerForm, self).__init__(*args, **kwargs)
199         self.fields['text'].initial = revision.text
200
201 class EditUserForm(forms.Form):
202     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}))
203     if settings.EDITABLE_SCREEN_NAME:
204         username = UserNameField(label=_('Screen name'))
205     realname = forms.CharField(label=_('Real name'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
206     website = forms.URLField(label=_('Website'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
207     city = forms.CharField(label=_('Location'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
208     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}))
209     about = forms.CharField(label=_('Profile'), required=False, widget=forms.Textarea(attrs={'cols' : 60}))
210
211     def __init__(self, user, *args, **kwargs):
212         super(EditUserForm, self).__init__(*args, **kwargs)
213         logging.debug('initializing the form')
214         if settings.EDITABLE_SCREEN_NAME:
215             self.fields['username'].initial = user.username
216             self.fields['username'].user_instance = user
217         self.fields['email'].initial = user.email
218         self.fields['realname'].initial = user.real_name
219         self.fields['website'].initial = user.website
220         self.fields['city'].initial = user.location
221
222         if user.date_of_birth is not None:
223             self.fields['birthday'].initial = user.date_of_birth
224         else:
225             self.fields['birthday'].initial = '1990-01-01'
226         self.fields['about'].initial = user.about
227         self.user = user
228
229     def clean_email(self):
230         """For security reason one unique email in database"""
231         if self.user.email != self.cleaned_data['email']:
232             #todo dry it, there is a similar thing in openidauth
233             if settings.EMAIL_UNIQUE == True:
234                 if 'email' in self.cleaned_data:
235                     try:
236                         user = User.objects.get(email = self.cleaned_data['email'])
237                     except User.DoesNotExist:
238                         return self.cleaned_data['email']
239                     except User.MultipleObjectsReturned:
240                         raise forms.ValidationError(_('this email has already been registered, please use another one'))
241                     raise forms.ValidationError(_('this email has already been registered, please use another one'))
242         return self.cleaned_data['email']
243
244
245 class SubscriptionSettingsForm(forms.Form):
246     member_joins = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
247     new_question = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
248     new_question_watched_tags = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
249     subscribed_questions = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
250
251     all_questions = forms.BooleanField(required=False, initial=False)
252     all_questions_watched_tags = forms.BooleanField(required=False, initial=False)
253     questions_asked = forms.BooleanField(required=False, initial=False)
254     questions_answered = forms.BooleanField(required=False, initial=False)
255     questions_commented = forms.BooleanField(required=False, initial=False)
256     questions_viewed = forms.BooleanField(required=False, initial=False)
257
258     notify_answers = forms.BooleanField(required=False, initial=False)
259     notify_reply_to_comments = forms.BooleanField(required=False, initial=False)
260     notify_comments_own_post = forms.BooleanField(required=False, initial=False)
261     notify_comments = forms.BooleanField(required=False, initial=False)
262     notify_accepted = forms.BooleanField(required=False, initial=False)
263