2 from datetime import date
3 from django import forms
4 from forum.models import *
5 from django.utils.translation import ugettext as _
7 from django.utils.encoding import smart_unicode
8 from general import NextUrlField, UserNameField
10 from forum import settings, REQUEST_HOLDER
12 from forum.modules import call_all_handlers
16 class TitleField(forms.CharField):
17 def __init__(self, *args, **kwargs):
18 super(TitleField, self).__init__(*args, **kwargs)
22 self.widget = forms.TextInput(attrs={'size' : 70, 'autocomplete' : 'off', 'maxlength' : self.max_length})
23 self.label = _('title')
24 self.help_text = _('please enter a descriptive title for your question')
27 def clean(self, value):
28 super(TitleField, self).clean(value)
30 if len(value) < settings.FORM_MIN_QUESTION_TITLE:
31 raise forms.ValidationError(_('title must be must be at least %s characters') % settings.FORM_MIN_QUESTION_TITLE)
35 class EditorField(forms.CharField):
36 def __init__(self, *args, **kwargs):
37 super(EditorField, self).__init__(*args, **kwargs)
39 self.widget = forms.Textarea(attrs={'id':'editor'})
40 self.label = _('content')
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)
51 def clean(self, value):
52 super(QuestionEditorField, self).clean(value)
54 if not bool(settings.FORM_EMPTY_QUESTION_BODY) and (len(re.sub('[ ]{2,}', ' ', value)) < settings.FORM_MIN_QUESTION_BODY):
55 raise forms.ValidationError(_('question content must be at least %s characters') % settings.FORM_MIN_QUESTION_BODY)
59 class AnswerEditorField(EditorField):
60 def __init__(self, *args, **kwargs):
61 super(AnswerEditorField, self).__init__(*args, **kwargs)
64 def clean(self, value):
65 super(AnswerEditorField, self).clean(value)
67 if len(re.sub('[ ]{2,}', ' ', value)) < settings.FORM_MIN_QUESTION_BODY:
68 raise forms.ValidationError(_('answer content must be at least %s characters') % settings.FORM_MIN_QUESTION_BODY)
73 class TagNamesField(forms.CharField):
74 def __init__(self, user=None, *args, **kwargs):
75 super(TagNamesField, self).__init__(*args, **kwargs)
78 self.widget = forms.TextInput(attrs={'size' : 50, 'autocomplete' : 'off'})
80 self.label = _('tags')
81 #self.help_text = _('please use space to separate tags (this enables autocomplete feature)')
82 self.help_text = _('Tags are short keywords, with no spaces within. At least %(min)s and up to %(max)s tags can be used.') % {
83 'min': settings.FORM_MIN_NUMBER_OF_TAGS, 'max': settings.FORM_MAX_NUMBER_OF_TAGS
88 def clean(self, value):
89 super(TagNamesField, self).clean(value)
91 value = super(TagNamesField, self).clean(value)
92 data = value.strip().lower()
94 split_re = re.compile(r'[ ,]+')
96 for tag in split_re.split(data):
99 if len(list) > settings.FORM_MAX_NUMBER_OF_TAGS or len(list) < settings.FORM_MIN_NUMBER_OF_TAGS:
100 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})
103 tagname_re = re.compile(r'^[\w+#\.-]+$', re.UNICODE)
104 for key,tag in list.items():
105 if len(tag) > settings.FORM_MAX_LENGTH_OF_TAG or len(tag) < settings.FORM_MIN_LENGTH_OF_TAG:
106 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})
107 if not tagname_re.match(tag):
108 raise forms.ValidationError(_('please use following characters in tags: letters , numbers, and characters \'.#-_\''))
109 # only keep one same tag
110 if tag not in list_temp and len(tag.strip()) > 0:
111 list_temp.append(tag)
113 if settings.LIMIT_TAG_CREATION and not self.user.can_create_tags():
114 existent = Tag.objects.filter(name__in=list_temp).values_list('name', flat=True)
116 if len(existent) < len(list_temp):
117 unexistent = [n for n in list_temp if not n in existent]
118 raise forms.ValidationError(_("You don't have enough reputation to create new tags. The following tags do not exist yet: %s") %
119 ', '.join(unexistent))
122 return u' '.join(list_temp)
124 class WikiField(forms.BooleanField):
125 def __init__(self, disabled=False, *args, **kwargs):
126 super(WikiField, self).__init__(*args, **kwargs)
127 self.required = False
128 self.label = _('community wiki')
129 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')
131 self.widget=forms.CheckboxInput(attrs={'disabled': "disabled"})
132 def clean(self,value):
135 class EmailNotifyField(forms.BooleanField):
136 def __init__(self, *args, **kwargs):
137 super(EmailNotifyField, self).__init__(*args, **kwargs)
138 self.required = False
139 self.widget.attrs['class'] = 'nomargin'
141 class SummaryField(forms.CharField):
142 def __init__(self, *args, **kwargs):
143 super(SummaryField, self).__init__(*args, **kwargs)
144 self.required = False
145 self.widget = forms.TextInput(attrs={'size' : 50, 'autocomplete' : 'off'})
146 self.max_length = 300
147 self.label = _('update summary:')
148 self.help_text = _('enter a brief summary of your revision (e.g. fixed spelling, grammar, improved style, this field is optional)')
151 class FeedbackForm(forms.Form):
152 message = forms.CharField(label=_('Your message:'), max_length=800,widget=forms.Textarea(attrs={'cols':60}))
153 next = NextUrlField()
155 def __init__(self, user, *args, **kwargs):
156 super(FeedbackForm, self).__init__(*args, **kwargs)
157 if not user.is_authenticated():
158 self.fields['name'] = forms.CharField(label=_('Your name:'), required=False)
159 self.fields['email'] = forms.EmailField(label=_('Email (not shared with anyone):'), required=True)
161 # Create anti spam fields
162 spam_fields = call_all_handlers('create_anti_spam_field')
164 spam_fields = dict(spam_fields)
165 for name, field in spam_fields.items():
166 self.fields[name] = field
168 self._anti_spam_fields = spam_fields.keys()
170 self._anti_spam_fields = []
174 class AskForm(forms.Form):
176 text = QuestionEditorField()
178 def __init__(self, data=None, user=None, *args, **kwargs):
179 super(AskForm, self).__init__(data, *args, **kwargs)
181 self.fields['tags'] = TagNamesField(user)
183 if not user.is_authenticated() or (int(user.reputation) < settings.CAPTCHA_IF_REP_LESS_THAN and not (user.is_superuser or user.is_staff)):
184 spam_fields = call_all_handlers('create_anti_spam_field')
186 spam_fields = dict(spam_fields)
187 for name, field in spam_fields.items():
188 self.fields[name] = field
190 self._anti_spam_fields = spam_fields.keys()
192 self._anti_spam_fields = []
195 self.fields['wiki'] = WikiField()
197 class AnswerForm(forms.Form):
198 text = AnswerEditorField()
201 def __init__(self, data=None, user=None, *args, **kwargs):
202 super(AnswerForm, self).__init__(data, *args, **kwargs)
204 if not user.is_authenticated() or (int(user.reputation) < settings.CAPTCHA_IF_REP_LESS_THAN and not (user.is_superuser or user.is_staff)):
205 spam_fields = call_all_handlers('create_anti_spam_field')
207 spam_fields = dict(spam_fields)
208 for name, field in spam_fields.items():
209 self.fields[name] = field
211 self._anti_spam_fields = spam_fields.keys()
213 self._anti_spam_fields = []
216 self.fields['wiki'] = WikiField()
218 class RetagQuestionForm(forms.Form):
219 tags = TagNamesField()
220 # initialize the default values
221 def __init__(self, question, *args, **kwargs):
222 super(RetagQuestionForm, self).__init__(*args, **kwargs)
223 self.fields['tags'].initial = question.tagnames
225 class RevisionForm(forms.Form):
227 Lists revisions of a Question or Answer
229 revision = forms.ChoiceField(widget=forms.Select(attrs={'style' : 'width:520px'}))
231 def __init__(self, post, *args, **kwargs):
232 super(RevisionForm, self).__init__(*args, **kwargs)
234 revisions = post.revisions.all().values_list('revision', 'author__username', 'revised_at', 'summary').order_by('-revised_at')
237 self.fields['revision'].choices = [
238 (r[0], u'%s - %s (%s) %s' % (r[0], smart_unicode(r[1]), r[2].strftime(date_format), r[3]))
241 self.fields['revision'].initial = post.active_revision.revision
243 class EditQuestionForm(forms.Form):
245 text = QuestionEditorField()
246 summary = SummaryField()
248 def __init__(self, question, user, revision=None, *args, **kwargs):
249 super(EditQuestionForm, self).__init__(*args, **kwargs)
252 revision = question.active_revision
254 self.fields['title'].initial = revision.title
255 self.fields['text'].initial = revision.body
257 self.fields['tags'] = TagNamesField(user)
258 self.fields['tags'].initial = revision.tagnames
260 if not user.is_authenticated() or (int(user.reputation) < settings.CAPTCHA_IF_REP_LESS_THAN and not (user.is_superuser or user.is_staff)):
261 spam_fields = call_all_handlers('create_anti_spam_field')
263 spam_fields = dict(spam_fields)
264 for name, field in spam_fields.items():
265 self.fields[name] = field
267 self._anti_spam_fields = spam_fields.keys()
269 self._anti_spam_fields = []
272 self.fields['wiki'] = WikiField(disabled=(question.nis.wiki and not user.can_cancel_wiki(question)), initial=question.nis.wiki)
274 class EditAnswerForm(forms.Form):
275 text = AnswerEditorField()
276 summary = SummaryField()
278 def __init__(self, answer, user, revision=None, *args, **kwargs):
279 super(EditAnswerForm, self).__init__(*args, **kwargs)
282 revision = answer.active_revision
284 self.fields['text'].initial = revision.body
286 if not user.is_authenticated() or (int(user.reputation) < settings.CAPTCHA_IF_REP_LESS_THAN and not (user.is_superuser or user.is_staff)):
287 spam_fields = call_all_handlers('create_anti_spam_field')
289 spam_fields = dict(spam_fields)
290 for name, field in spam_fields.items():
291 self.fields[name] = field
293 self._anti_spam_fields = spam_fields.keys()
295 self._anti_spam_fields = []
298 self.fields['wiki'] = WikiField(disabled=(answer.nis.wiki and not user.can_cancel_wiki(answer)), initial=answer.nis.wiki)
300 class EditUserForm(forms.Form):
301 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}))
302 realname = forms.CharField(label=_('Real name'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
303 website = forms.URLField(label=_('Website'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
304 city = forms.CharField(label=_('Location'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
305 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}))
306 about = forms.CharField(label=_('Profile'), required=False, widget=forms.Textarea(attrs={'cols' : 60}))
308 def __init__(self, user, *args, **kwargs):
309 super(EditUserForm, self).__init__(*args, **kwargs)
310 if settings.EDITABLE_SCREEN_NAME or (REQUEST_HOLDER.request.user.is_authenticated() and REQUEST_HOLDER.request.user.is_superuser):
311 self.fields['username'] = UserNameField(label=_('Screen name'))
312 self.fields['username'].initial = user.username
313 self.fields['username'].user_instance = user
314 self.fields['email'].initial = user.email
315 self.fields['realname'].initial = user.real_name
316 self.fields['website'].initial = user.website
317 self.fields['city'].initial = user.location
319 if user.date_of_birth is not None:
320 self.fields['birthday'].initial = user.date_of_birth
322 self.fields['about'].initial = user.about
325 def clean_email(self):
326 if self.user.email != self.cleaned_data['email']:
327 if settings.EMAIL_UNIQUE:
328 if 'email' in self.cleaned_data:
329 from forum.models import User
331 User.objects.get(email = self.cleaned_data['email'])
332 except User.DoesNotExist:
333 return self.cleaned_data['email']
334 except User.MultipleObjectsReturned:
335 logging.error("Found multiple users sharing the same email: %s" % self.cleaned_data['email'])
337 raise forms.ValidationError(_('this email has already been registered, please use another one'))
338 return self.cleaned_data['email']
341 NOTIFICATION_CHOICES = (
342 ('i', _('Instantly')),
345 ('n', _('No notifications')),
348 class SubscriptionSettingsForm(forms.ModelForm):
349 enable_notifications = forms.BooleanField(widget=forms.HiddenInput, required=False)
350 member_joins = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
351 new_question = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
352 new_question_watched_tags = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
353 subscribed_questions = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
356 model = SubscriptionSettings
357 fields = ['enable_notifications', 'member_joins', 'new_question', 'new_question_watched_tags', 'subscribed_questions']
359 class UserPreferencesForm(forms.Form):
360 sticky_sorts = forms.BooleanField(required=False, initial=False)