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.encoding import smart_unicode
9 from django.utils.safestring import mark_safe
10 from general import NextUrlField, UserNameField, SetPasswordForm
12 from forum import settings
14 from forum.modules import call_all_handlers
18 class TitleField(forms.CharField):
19 def __init__(self, *args, **kwargs):
20 super(TitleField, self).__init__(*args, **kwargs)
23 self.widget = forms.TextInput(attrs={'size' : 70, 'autocomplete' : 'off', 'maxlength' : self.max_length})
24 self.label = _('title')
25 self.help_text = _('please enter a descriptive title for your question')
28 def clean(self, value):
29 super(TitleField, self).clean(value);
31 if len(value) < settings.FORM_MIN_QUESTION_TITLE:
32 raise forms.ValidationError(_('title must be must be at least %s characters') % settings.FORM_MIN_QUESTION_TITLE)
36 class EditorField(forms.CharField):
37 def __init__(self, *args, **kwargs):
38 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 if not bool(settings.FORM_EMPTY_QUESTION_BODY) and (len(re.sub('[ ]{2,}', ' ', value)) < settings.FORM_MIN_QUESTION_BODY):
53 raise forms.ValidationError(_('question content must be at least %s characters') % settings.FORM_MIN_QUESTION_BODY)
57 class AnswerEditorField(EditorField):
58 def __init__(self, *args, **kwargs):
59 super(AnswerEditorField, self).__init__(*args, **kwargs)
62 def clean(self, value):
63 if len(re.sub('[ ]{2,}', ' ', value)) < settings.FORM_MIN_QUESTION_BODY:
64 raise forms.ValidationError(_('answer content must be at least %s characters') % settings.FORM_MIN_QUESTION_BODY)
69 class TagNamesField(forms.CharField):
70 def __init__(self, user=None, *args, **kwargs):
71 super(TagNamesField, self).__init__(*args, **kwargs)
73 self.widget = forms.TextInput(attrs={'size' : 50, 'autocomplete' : 'off'})
75 self.label = _('tags')
76 #self.help_text = _('please use space to separate tags (this enables autocomplete feature)')
77 self.help_text = _('Tags are short keywords, with no spaces within. At least %(min)s and up to %(max)s tags can be used.') % {
78 'min': settings.FORM_MIN_NUMBER_OF_TAGS, 'max': settings.FORM_MAX_NUMBER_OF_TAGS
83 def clean(self, value):
84 value = super(TagNamesField, self).clean(value)
85 data = value.strip().lower()
87 split_re = re.compile(r'[ ,]+')
89 for tag in split_re.split(data):
92 if len(list) > settings.FORM_MAX_NUMBER_OF_TAGS or len(list) < settings.FORM_MIN_NUMBER_OF_TAGS:
93 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})
96 tagname_re = re.compile(r'^[\w+\.-]+$', re.UNICODE)
97 for key,tag in list.items():
98 if len(tag) > settings.FORM_MAX_LENGTH_OF_TAG or len(tag) < settings.FORM_MIN_LENGTH_OF_TAG:
99 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})
100 if not tagname_re.match(tag):
101 raise forms.ValidationError(_('please use following characters in tags: letters , numbers, and characters \'.-_\''))
102 # only keep one same tag
103 if tag not in list_temp and len(tag.strip()) > 0:
104 list_temp.append(tag)
106 if settings.LIMIT_TAG_CREATION and not self.user.can_create_tags():
107 existent = Tag.objects.filter(name__in=list_temp).values_list('name', flat=True)
109 if len(existent) < len(list_temp):
110 unexistent = [n for n in list_temp if not n in existent]
111 raise forms.ValidationError(_("You don't have enough reputation to create new tags. The following tags do not exist yet: %s") %
112 ', '.join(unexistent))
115 return u' '.join(list_temp)
117 class WikiField(forms.BooleanField):
118 def __init__(self, disabled=False, *args, **kwargs):
119 super(WikiField, self).__init__(*args, **kwargs)
120 self.required = False
121 self.label = _('community wiki')
122 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')
124 self.widget=forms.CheckboxInput(attrs={'disabled': "disabled"})
125 def clean(self,value):
128 class EmailNotifyField(forms.BooleanField):
129 def __init__(self, *args, **kwargs):
130 super(EmailNotifyField, self).__init__(*args, **kwargs)
131 self.required = False
132 self.widget.attrs['class'] = 'nomargin'
134 class SummaryField(forms.CharField):
135 def __init__(self, *args, **kwargs):
136 super(SummaryField, self).__init__(*args, **kwargs)
137 self.required = False
138 self.widget = forms.TextInput(attrs={'size' : 50, 'autocomplete' : 'off'})
139 self.max_length = 300
140 self.label = _('update summary:')
141 self.help_text = _('enter a brief summary of your revision (e.g. fixed spelling, grammar, improved style, this field is optional)')
144 class FeedbackForm(forms.Form):
145 message = forms.CharField(label=_('Your message:'), max_length=800,widget=forms.Textarea(attrs={'cols':60}))
146 next = NextUrlField()
148 def __init__(self, user, *args, **kwargs):
149 super(FeedbackForm, self).__init__(*args, **kwargs)
150 if not user.is_authenticated():
151 self.fields['name'] = forms.CharField(label=_('Your name:'), required=False)
152 self.fields['email'] = forms.EmailField(label=_('Email (not shared with anyone):'), required=True)
156 class AskForm(forms.Form):
158 text = QuestionEditorField()
160 def __init__(self, data=None, user=None, *args, **kwargs):
161 super(AskForm, self).__init__(data, *args, **kwargs)
163 self.fields['tags'] = TagNamesField(user)
165 if int(user.reputation) < settings.CAPTCHA_IF_REP_LESS_THAN and not (user.is_superuser or user.is_staff):
166 spam_fields = call_all_handlers('create_anti_spam_field')
168 spam_fields = dict(spam_fields)
169 for name, field in spam_fields.items():
170 self.fields[name] = field
172 self._anti_spam_fields = spam_fields.keys()
174 self._anti_spam_fields = []
177 self.fields['wiki'] = WikiField()
179 class AnswerForm(forms.Form):
180 text = AnswerEditorField()
183 def __init__(self, data=None, user=None, *args, **kwargs):
184 super(AnswerForm, self).__init__(data, *args, **kwargs)
186 if int(user.reputation) < settings.CAPTCHA_IF_REP_LESS_THAN and not (user.is_superuser or user.is_staff):
187 spam_fields = call_all_handlers('create_anti_spam_field')
189 spam_fields = dict(spam_fields)
190 for name, field in spam_fields.items():
191 self.fields[name] = field
193 self._anti_spam_fields = spam_fields.keys()
195 self._anti_spam_fields = []
198 self.fields['wiki'] = WikiField()
200 class RetagQuestionForm(forms.Form):
201 tags = TagNamesField()
202 # initialize the default values
203 def __init__(self, question, *args, **kwargs):
204 super(RetagQuestionForm, self).__init__(*args, **kwargs)
205 self.fields['tags'].initial = question.tagnames
207 class RevisionForm(forms.Form):
209 Lists revisions of a Question or Answer
211 revision = forms.ChoiceField(widget=forms.Select(attrs={'style' : 'width:520px'}))
213 def __init__(self, post, *args, **kwargs):
214 super(RevisionForm, self).__init__(*args, **kwargs)
216 revisions = post.revisions.all().values_list('revision', 'author__username', 'revised_at', 'summary').order_by('-revised_at')
219 self.fields['revision'].choices = [
220 (r[0], u'%s - %s (%s) %s' % (r[0], smart_unicode(r[1]), r[2].strftime(date_format), r[3]))
223 self.fields['revision'].initial = post.active_revision.revision
225 class EditQuestionForm(forms.Form):
227 text = QuestionEditorField()
228 summary = SummaryField()
230 def __init__(self, question, user, revision=None, *args, **kwargs):
231 super(EditQuestionForm, self).__init__(*args, **kwargs)
234 revision = question.active_revision
236 self.fields['title'].initial = revision.title
237 self.fields['text'].initial = revision.body
239 self.fields['tags'] = TagNamesField(user)
240 self.fields['tags'].initial = revision.tagnames
242 if int(user.reputation) < settings.CAPTCHA_IF_REP_LESS_THAN and not (user.is_superuser or user.is_staff):
243 spam_fields = call_all_handlers('create_anti_spam_field')
245 spam_fields = dict(spam_fields)
246 for name, field in spam_fields.items():
247 self.fields[name] = field
249 self._anti_spam_fields = spam_fields.keys()
251 self._anti_spam_fields = []
254 self.fields['wiki'] = WikiField(disabled=(question.nis.wiki and not user.can_cancel_wiki(question)), initial=question.nis.wiki)
256 class EditAnswerForm(forms.Form):
257 text = AnswerEditorField()
258 summary = SummaryField()
260 def __init__(self, answer, user, revision=None, *args, **kwargs):
261 super(EditAnswerForm, self).__init__(*args, **kwargs)
264 revision = answer.active_revision
266 self.fields['text'].initial = revision.body
268 if int(user.reputation) < settings.CAPTCHA_IF_REP_LESS_THAN and not (user.is_superuser or user.is_staff):
269 spam_fields = call_all_handlers('create_anti_spam_field')
271 spam_fields = dict(spam_fields)
272 for name, field in spam_fields.items():
273 self.fields[name] = field
275 self._anti_spam_fields = spam_fields.keys()
277 self._anti_spam_fields = []
280 self.fields['wiki'] = WikiField(disabled=(answer.nis.wiki and not user.can_cancel_wiki(answer)), initial=answer.nis.wiki)
282 class EditUserForm(forms.Form):
283 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}))
284 realname = forms.CharField(label=_('Real name'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
285 website = forms.URLField(label=_('Website'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
286 city = forms.CharField(label=_('Location'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
287 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}))
288 about = forms.CharField(label=_('Profile'), required=False, widget=forms.Textarea(attrs={'cols' : 60}))
290 def __init__(self, user, *args, **kwargs):
291 super(EditUserForm, self).__init__(*args, **kwargs)
292 if settings.EDITABLE_SCREEN_NAME:
293 self.fields['username'] = UserNameField(label=_('Screen name'))
294 self.fields['username'].initial = user.username
295 self.fields['username'].user_instance = user
296 self.fields['email'].initial = user.email
297 self.fields['realname'].initial = user.real_name
298 self.fields['website'].initial = user.website
299 self.fields['city'].initial = user.location
301 if user.date_of_birth is not None:
302 self.fields['birthday'].initial = user.date_of_birth
304 self.fields['about'].initial = user.about
307 def clean_email(self):
308 if self.user.email != self.cleaned_data['email']:
309 if settings.EMAIL_UNIQUE == True:
310 if 'email' in self.cleaned_data:
311 from forum.models import User
313 User.objects.get(email = self.cleaned_data['email'])
314 except User.DoesNotExist:
315 return self.cleaned_data['email']
316 except User.MultipleObjectsReturned:
317 logging.error("Found multiple users sharing the same email: %s" % self.cleaned_data['email'])
319 raise forms.ValidationError(_('this email has already been registered, please use another one'))
320 return self.cleaned_data['email']
323 NOTIFICATION_CHOICES = (
324 ('i', _('Instantly')),
327 ('n', _('No notifications')),
330 class SubscriptionSettingsForm(forms.ModelForm):
331 enable_notifications = forms.BooleanField(widget=forms.HiddenInput, required=False)
332 member_joins = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
333 new_question = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
334 new_question_watched_tags = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
335 subscribed_questions = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
338 model = SubscriptionSettings
340 class UserPreferencesForm(forms.Form):
341 sticky_sorts = forms.BooleanField(required=False, initial=False)