2 from datetime import date
3 from django import forms
4 from forum.models import *
5 from django.utils.translation import ugettext as _
6 from django.contrib.humanize.templatetags.humanize import apnumber
8 from django.utils.safestring import mark_safe
9 from general import NextUrlField, UserNameField, SetPasswordForm
10 from forum import settings
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)
21 self.widget = forms.TextInput(attrs={'size' : 70, 'autocomplete' : 'off', 'maxlength' : self.max_length})
22 self.label = _('title')
23 self.help_text = _('please enter a descriptive title for your question')
26 def clean(self, value):
27 if len(value) < settings.FORM_MIN_QUESTION_TITLE:
28 raise forms.ValidationError(_('title must be must be at least %s characters') % settings.FORM_MIN_QUESTION_TITLE)
32 class EditorField(forms.CharField):
33 def __init__(self, *args, **kwargs):
34 super(EditorField, self).__init__(*args, **kwargs)
35 self.widget = forms.Textarea(attrs={'id':'editor'})
36 self.label = _('content')
41 class QuestionEditorField(EditorField):
42 def __init__(self, *args, **kwargs):
43 super(QuestionEditorField, self).__init__(*args, **kwargs)
44 self.required = not bool(settings.FORM_EMPTY_QUESTION_BODY)
47 def clean(self, value):
48 if not bool(settings.FORM_EMPTY_QUESTION_BODY) and (len(re.sub('[ ]{2,}', ' ', value)) < settings.FORM_MIN_QUESTION_BODY):
49 raise forms.ValidationError(_('question content must be at least %s characters') % settings.FORM_MIN_QUESTION_BODY)
53 class AnswerEditorField(EditorField):
54 def __init__(self, *args, **kwargs):
55 super(AnswerEditorField, self).__init__(*args, **kwargs)
58 def clean(self, value):
59 if len(re.sub('[ ]{2,}', ' ', value)) < settings.FORM_MIN_QUESTION_BODY:
60 raise forms.ValidationError(_('answer content must be at least %s characters') % settings.FORM_MIN_QUESTION_BODY)
65 class TagNamesField(forms.CharField):
66 def __init__(self, user=None, *args, **kwargs):
67 super(TagNamesField, self).__init__(*args, **kwargs)
69 self.widget = forms.TextInput(attrs={'size' : 50, 'autocomplete' : 'off'})
71 self.label = _('tags')
72 #self.help_text = _('please use space to separate tags (this enables autocomplete feature)')
73 self.help_text = _('Tags are short keywords, with no spaces within. At least %(min)s and up to %(max)s tags can be used.') % {
74 'min': settings.FORM_MIN_NUMBER_OF_TAGS, 'max': settings.FORM_MAX_NUMBER_OF_TAGS
79 def clean(self, value):
80 value = super(TagNamesField, self).clean(value)
81 data = value.strip().lower()
83 split_re = re.compile(r'[ ,]+')
85 for tag in split_re.split(data):
88 if len(list) > settings.FORM_MAX_NUMBER_OF_TAGS or len(list) < settings.FORM_MIN_NUMBER_OF_TAGS:
89 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})
92 tagname_re = re.compile(r'^[\w+\.-]+$', re.UNICODE)
93 for key,tag in list.items():
94 if len(tag) > settings.FORM_MAX_LENGTH_OF_TAG or len(tag) < settings.FORM_MIN_LENGTH_OF_TAG:
95 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})
96 if not tagname_re.match(tag):
97 raise forms.ValidationError(_('please use following characters in tags: letters , numbers, and characters \'.-_\''))
98 # only keep one same tag
99 if tag not in list_temp and len(tag.strip()) > 0:
100 list_temp.append(tag)
102 if settings.LIMIT_TAG_CREATION and not self.user.can_create_tags():
103 existent = Tag.objects.filter(name__in=list_temp).values_list('name', flat=True)
105 if len(existent) < len(list_temp):
106 unexistent = [n for n in list_temp if not n in existent]
107 raise forms.ValidationError(_("You don't have enough reputation to create new tags. The following tags do not exist yet: %s") %
108 ', '.join(unexistent))
111 return u' '.join(list_temp)
113 class WikiField(forms.BooleanField):
114 def __init__(self, disabled=False, *args, **kwargs):
115 super(WikiField, self).__init__(*args, **kwargs)
116 self.required = False
117 self.label = _('community wiki')
118 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')
120 self.widget=forms.CheckboxInput(attrs={'disabled': "disabled"})
121 def clean(self,value):
124 class EmailNotifyField(forms.BooleanField):
125 def __init__(self, *args, **kwargs):
126 super(EmailNotifyField, self).__init__(*args, **kwargs)
127 self.required = False
128 self.widget.attrs['class'] = 'nomargin'
130 class SummaryField(forms.CharField):
131 def __init__(self, *args, **kwargs):
132 super(SummaryField, self).__init__(*args, **kwargs)
133 self.required = False
134 self.widget = forms.TextInput(attrs={'size' : 50, 'autocomplete' : 'off'})
135 self.max_length = 300
136 self.label = _('update summary:')
137 self.help_text = _('enter a brief summary of your revision (e.g. fixed spelling, grammar, improved style, this field is optional)')
140 class FeedbackForm(forms.Form):
141 message = forms.CharField(label=_('Your message:'), max_length=800,widget=forms.Textarea(attrs={'cols':60}))
142 next = NextUrlField()
144 def __init__(self, user, *args, **kwargs):
145 super(FeedbackForm, self).__init__(*args, **kwargs)
146 if not user.is_authenticated():
147 self.fields['name'] = forms.CharField(label=_('Your name:'), required=False)
148 self.fields['email'] = forms.EmailField(label=_('Email (not shared with anyone):'), required=True)
152 class AskForm(forms.Form):
154 text = QuestionEditorField()
156 def __init__(self, data=None, user=None, *args, **kwargs):
157 super(AskForm, self).__init__(data, *args, **kwargs)
159 self.fields['tags'] = TagNamesField(user)
161 if int(user.reputation) < settings.CAPTCHA_IF_REP_LESS_THAN and not (user.is_superuser or user.is_staff):
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 = []
173 self.fields['wiki'] = WikiField()
175 class AnswerForm(forms.Form):
176 text = AnswerEditorField()
179 def __init__(self, data=None, user=None, *args, **kwargs):
180 super(AnswerForm, self).__init__(data, *args, **kwargs)
182 if int(user.reputation) < settings.CAPTCHA_IF_REP_LESS_THAN and not (user.is_superuser or user.is_staff):
183 spam_fields = call_all_handlers('create_anti_spam_field')
185 spam_fields = dict(spam_fields)
186 for name, field in spam_fields.items():
187 self.fields[name] = field
189 self._anti_spam_fields = spam_fields.keys()
191 self._anti_spam_fields = []
194 self.fields['wiki'] = WikiField()
196 class RetagQuestionForm(forms.Form):
197 tags = TagNamesField()
198 # initialize the default values
199 def __init__(self, question, *args, **kwargs):
200 super(RetagQuestionForm, self).__init__(*args, **kwargs)
201 self.fields['tags'].initial = question.tagnames
203 class RevisionForm(forms.Form):
205 Lists revisions of a Question or Answer
207 revision = forms.ChoiceField(widget=forms.Select(attrs={'style' : 'width:520px'}))
209 def __init__(self, post, *args, **kwargs):
210 super(RevisionForm, self).__init__(*args, **kwargs)
212 revisions = post.revisions.all().values_list('revision', 'author__username', 'revised_at', 'summary').order_by('-revised_at')
215 self.fields['revision'].choices = [
216 (r[0], u'%s - %s (%s) %s' % (r[0], r[1], r[2].strftime(date_format), r[3]))
219 self.fields['revision'].initial = post.active_revision.revision
221 class EditQuestionForm(forms.Form):
223 text = QuestionEditorField()
224 summary = SummaryField()
226 def __init__(self, question, user, revision=None, *args, **kwargs):
227 super(EditQuestionForm, self).__init__(*args, **kwargs)
230 revision = question.active_revision
232 self.fields['title'].initial = revision.title
233 self.fields['text'].initial = revision.body
235 self.fields['tags'] = TagNamesField(user)
236 self.fields['tags'].initial = revision.tagnames
238 if int(user.reputation) < settings.CAPTCHA_IF_REP_LESS_THAN and not (user.is_superuser or user.is_staff):
239 spam_fields = call_all_handlers('create_anti_spam_field')
241 spam_fields = dict(spam_fields)
242 for name, field in spam_fields.items():
243 self.fields[name] = field
245 self._anti_spam_fields = spam_fields.keys()
247 self._anti_spam_fields = []
250 self.fields['wiki'] = WikiField(disabled=(question.nis.wiki and not user.can_cancel_wiki(question)), initial=question.nis.wiki)
252 class EditAnswerForm(forms.Form):
253 text = AnswerEditorField()
254 summary = SummaryField()
256 def __init__(self, answer, user, revision=None, *args, **kwargs):
257 super(EditAnswerForm, self).__init__(*args, **kwargs)
260 revision = answer.active_revision
262 self.fields['text'].initial = revision.body
264 if int(user.reputation) < settings.CAPTCHA_IF_REP_LESS_THAN and not (user.is_superuser or user.is_staff):
265 spam_fields = call_all_handlers('create_anti_spam_field')
267 spam_fields = dict(spam_fields)
268 for name, field in spam_fields.items():
269 self.fields[name] = field
271 self._anti_spam_fields = spam_fields.keys()
273 self._anti_spam_fields = []
276 self.fields['wiki'] = WikiField(disabled=(answer.nis.wiki and not user.can_cancel_wiki(answer)), initial=answer.nis.wiki)
278 class EditUserForm(forms.Form):
279 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}))
280 realname = forms.CharField(label=_('Real name'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
281 website = forms.URLField(label=_('Website'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
282 city = forms.CharField(label=_('Location'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
283 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}))
284 about = forms.CharField(label=_('Profile'), required=False, widget=forms.Textarea(attrs={'cols' : 60}))
286 def __init__(self, user, *args, **kwargs):
287 super(EditUserForm, self).__init__(*args, **kwargs)
288 if settings.EDITABLE_SCREEN_NAME:
289 self.fields['username'] = UserNameField(label=_('Screen name'))
290 self.fields['username'].initial = user.username
291 self.fields['username'].user_instance = user
292 self.fields['email'].initial = user.email
293 self.fields['realname'].initial = user.real_name
294 self.fields['website'].initial = user.website
295 self.fields['city'].initial = user.location
297 if user.date_of_birth is not None:
298 self.fields['birthday'].initial = user.date_of_birth
300 self.fields['birthday'].initial = '1990-01-01'
301 self.fields['about'].initial = user.about
304 def clean_email(self):
305 if self.user.email != self.cleaned_data['email']:
306 if settings.EMAIL_UNIQUE == True:
307 if 'email' in self.cleaned_data:
308 from forum.models import User
310 User.objects.get(email = self.cleaned_data['email'])
311 except User.DoesNotExist:
312 return self.cleaned_data['email']
313 except User.MultipleObjectsReturned:
314 logging.error("Found multiple users sharing the same email: %s" % self.cleaned_data['email'])
316 raise forms.ValidationError(_('this email has already been registered, please use another one'))
317 return self.cleaned_data['email']
320 NOTIFICATION_CHOICES = (
321 ('i', _('Instantly')),
324 ('n', _('No notifications')),
327 class SubscriptionSettingsForm(forms.ModelForm):
328 enable_notifications = forms.BooleanField(widget=forms.HiddenInput, required=False)
329 member_joins = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
330 new_question = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
331 new_question_watched_tags = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
332 subscribed_questions = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
335 model = SubscriptionSettings
337 class UserPreferencesForm(forms.Form):
338 sticky_sorts = forms.BooleanField(required=False, initial=False)