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 if len(value) < settings.FORM_MIN_QUESTION_TITLE:
30 raise forms.ValidationError(_('title must be must be at least %s characters') % settings.FORM_MIN_QUESTION_TITLE)
34 class EditorField(forms.CharField):
35 def __init__(self, *args, **kwargs):
36 super(EditorField, self).__init__(*args, **kwargs)
37 self.widget = forms.Textarea(attrs={'id':'editor'})
38 self.label = _('content')
43 class QuestionEditorField(EditorField):
44 def __init__(self, *args, **kwargs):
45 super(QuestionEditorField, self).__init__(*args, **kwargs)
46 self.required = not bool(settings.FORM_EMPTY_QUESTION_BODY)
49 def clean(self, value):
50 if not bool(settings.FORM_EMPTY_QUESTION_BODY) and (len(re.sub('[ ]{2,}', ' ', value)) < settings.FORM_MIN_QUESTION_BODY):
51 raise forms.ValidationError(_('question content must be at least %s characters') % settings.FORM_MIN_QUESTION_BODY)
55 class AnswerEditorField(EditorField):
56 def __init__(self, *args, **kwargs):
57 super(AnswerEditorField, self).__init__(*args, **kwargs)
60 def clean(self, value):
61 if len(re.sub('[ ]{2,}', ' ', value)) < settings.FORM_MIN_QUESTION_BODY:
62 raise forms.ValidationError(_('answer content must be at least %s characters') % settings.FORM_MIN_QUESTION_BODY)
67 class TagNamesField(forms.CharField):
68 def __init__(self, user=None, *args, **kwargs):
69 super(TagNamesField, self).__init__(*args, **kwargs)
71 self.widget = forms.TextInput(attrs={'size' : 50, 'autocomplete' : 'off'})
73 self.label = _('tags')
74 #self.help_text = _('please use space to separate tags (this enables autocomplete feature)')
75 self.help_text = _('Tags are short keywords, with no spaces within. At least %(min)s and up to %(max)s tags can be used.') % {
76 'min': settings.FORM_MIN_NUMBER_OF_TAGS, 'max': settings.FORM_MAX_NUMBER_OF_TAGS
81 def clean(self, value):
82 value = super(TagNamesField, self).clean(value)
83 data = value.strip().lower()
85 split_re = re.compile(r'[ ,]+')
87 for tag in split_re.split(data):
90 if len(list) > settings.FORM_MAX_NUMBER_OF_TAGS or len(list) < settings.FORM_MIN_NUMBER_OF_TAGS:
91 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})
94 tagname_re = re.compile(r'^[\w+\.-]+$', re.UNICODE)
95 for key,tag in list.items():
96 if len(tag) > settings.FORM_MAX_LENGTH_OF_TAG or len(tag) < settings.FORM_MIN_LENGTH_OF_TAG:
97 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})
98 if not tagname_re.match(tag):
99 raise forms.ValidationError(_('please use following characters in tags: letters , numbers, and characters \'.-_\''))
100 # only keep one same tag
101 if tag not in list_temp and len(tag.strip()) > 0:
102 list_temp.append(tag)
104 if settings.LIMIT_TAG_CREATION and not self.user.can_create_tags():
105 existent = Tag.objects.filter(name__in=list_temp).values_list('name', flat=True)
107 if len(existent) < len(list_temp):
108 unexistent = [n for n in list_temp if not n in existent]
109 raise forms.ValidationError(_("You don't have enough reputation to create new tags. The following tags do not exist yet: %s") %
110 ', '.join(unexistent))
113 return u' '.join(list_temp)
115 class WikiField(forms.BooleanField):
116 def __init__(self, disabled=False, *args, **kwargs):
117 super(WikiField, self).__init__(*args, **kwargs)
118 self.required = False
119 self.label = _('community wiki')
120 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')
122 self.widget=forms.CheckboxInput(attrs={'disabled': "disabled"})
123 def clean(self,value):
126 class EmailNotifyField(forms.BooleanField):
127 def __init__(self, *args, **kwargs):
128 super(EmailNotifyField, self).__init__(*args, **kwargs)
129 self.required = False
130 self.widget.attrs['class'] = 'nomargin'
132 class SummaryField(forms.CharField):
133 def __init__(self, *args, **kwargs):
134 super(SummaryField, self).__init__(*args, **kwargs)
135 self.required = False
136 self.widget = forms.TextInput(attrs={'size' : 50, 'autocomplete' : 'off'})
137 self.max_length = 300
138 self.label = _('update summary:')
139 self.help_text = _('enter a brief summary of your revision (e.g. fixed spelling, grammar, improved style, this field is optional)')
142 class FeedbackForm(forms.Form):
143 message = forms.CharField(label=_('Your message:'), max_length=800,widget=forms.Textarea(attrs={'cols':60}))
144 next = NextUrlField()
146 def __init__(self, user, *args, **kwargs):
147 super(FeedbackForm, self).__init__(*args, **kwargs)
148 if not user.is_authenticated():
149 self.fields['name'] = forms.CharField(label=_('Your name:'), required=False)
150 self.fields['email'] = forms.EmailField(label=_('Email (not shared with anyone):'), required=True)
154 class AskForm(forms.Form):
156 text = QuestionEditorField()
158 def __init__(self, data=None, user=None, *args, **kwargs):
159 super(AskForm, self).__init__(data, *args, **kwargs)
161 self.fields['tags'] = TagNamesField(user)
163 if int(user.reputation) < settings.CAPTCHA_IF_REP_LESS_THAN and not (user.is_superuser or user.is_staff):
164 spam_fields = call_all_handlers('create_anti_spam_field')
166 spam_fields = dict(spam_fields)
167 for name, field in spam_fields.items():
168 self.fields[name] = field
170 self._anti_spam_fields = spam_fields.keys()
172 self._anti_spam_fields = []
175 self.fields['wiki'] = WikiField()
177 class AnswerForm(forms.Form):
178 text = AnswerEditorField()
181 def __init__(self, data=None, user=None, *args, **kwargs):
182 super(AnswerForm, self).__init__(data, *args, **kwargs)
184 if int(user.reputation) < settings.CAPTCHA_IF_REP_LESS_THAN and not (user.is_superuser or user.is_staff):
185 spam_fields = call_all_handlers('create_anti_spam_field')
187 spam_fields = dict(spam_fields)
188 for name, field in spam_fields.items():
189 self.fields[name] = field
191 self._anti_spam_fields = spam_fields.keys()
193 self._anti_spam_fields = []
196 self.fields['wiki'] = WikiField()
198 class RetagQuestionForm(forms.Form):
199 tags = TagNamesField()
200 # initialize the default values
201 def __init__(self, question, *args, **kwargs):
202 super(RetagQuestionForm, self).__init__(*args, **kwargs)
203 self.fields['tags'].initial = question.tagnames
205 class RevisionForm(forms.Form):
207 Lists revisions of a Question or Answer
209 revision = forms.ChoiceField(widget=forms.Select(attrs={'style' : 'width:520px'}))
211 def __init__(self, post, *args, **kwargs):
212 super(RevisionForm, self).__init__(*args, **kwargs)
214 revisions = post.revisions.all().values_list('revision', 'author__username', 'revised_at', 'summary').order_by('-revised_at')
217 self.fields['revision'].choices = [
218 (r[0], u'%s - %s (%s) %s' % (r[0], smart_unicode(r[1]), r[2].strftime(date_format), r[3]))
221 self.fields['revision'].initial = post.active_revision.revision
223 class EditQuestionForm(forms.Form):
225 text = QuestionEditorField()
226 summary = SummaryField()
228 def __init__(self, question, user, revision=None, *args, **kwargs):
229 super(EditQuestionForm, self).__init__(*args, **kwargs)
232 revision = question.active_revision
234 self.fields['title'].initial = revision.title
235 self.fields['text'].initial = revision.body
237 self.fields['tags'] = TagNamesField(user)
238 self.fields['tags'].initial = revision.tagnames
240 if int(user.reputation) < settings.CAPTCHA_IF_REP_LESS_THAN and not (user.is_superuser or user.is_staff):
241 spam_fields = call_all_handlers('create_anti_spam_field')
243 spam_fields = dict(spam_fields)
244 for name, field in spam_fields.items():
245 self.fields[name] = field
247 self._anti_spam_fields = spam_fields.keys()
249 self._anti_spam_fields = []
252 self.fields['wiki'] = WikiField(disabled=(question.nis.wiki and not user.can_cancel_wiki(question)), initial=question.nis.wiki)
254 class EditAnswerForm(forms.Form):
255 text = AnswerEditorField()
256 summary = SummaryField()
258 def __init__(self, answer, user, revision=None, *args, **kwargs):
259 super(EditAnswerForm, self).__init__(*args, **kwargs)
262 revision = answer.active_revision
264 self.fields['text'].initial = revision.body
266 if int(user.reputation) < settings.CAPTCHA_IF_REP_LESS_THAN and not (user.is_superuser or user.is_staff):
267 spam_fields = call_all_handlers('create_anti_spam_field')
269 spam_fields = dict(spam_fields)
270 for name, field in spam_fields.items():
271 self.fields[name] = field
273 self._anti_spam_fields = spam_fields.keys()
275 self._anti_spam_fields = []
278 self.fields['wiki'] = WikiField(disabled=(answer.nis.wiki and not user.can_cancel_wiki(answer)), initial=answer.nis.wiki)
280 class EditUserForm(forms.Form):
281 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}))
282 realname = forms.CharField(label=_('Real name'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
283 website = forms.URLField(label=_('Website'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
284 city = forms.CharField(label=_('Location'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
285 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}))
286 about = forms.CharField(label=_('Profile'), required=False, widget=forms.Textarea(attrs={'cols' : 60}))
288 def __init__(self, user, *args, **kwargs):
289 super(EditUserForm, self).__init__(*args, **kwargs)
290 if settings.EDITABLE_SCREEN_NAME:
291 self.fields['username'] = UserNameField(label=_('Screen name'))
292 self.fields['username'].initial = user.username
293 self.fields['username'].user_instance = user
294 self.fields['email'].initial = user.email
295 self.fields['realname'].initial = user.real_name
296 self.fields['website'].initial = user.website
297 self.fields['city'].initial = user.location
299 if user.date_of_birth is not None:
300 self.fields['birthday'].initial = user.date_of_birth
302 self.fields['about'].initial = user.about
305 def clean_email(self):
306 if self.user.email != self.cleaned_data['email']:
307 if settings.EMAIL_UNIQUE == True:
308 if 'email' in self.cleaned_data:
309 from forum.models import User
311 User.objects.get(email = self.cleaned_data['email'])
312 except User.DoesNotExist:
313 return self.cleaned_data['email']
314 except User.MultipleObjectsReturned:
315 logging.error("Found multiple users sharing the same email: %s" % self.cleaned_data['email'])
317 raise forms.ValidationError(_('this email has already been registered, please use another one'))
318 return self.cleaned_data['email']
321 NOTIFICATION_CHOICES = (
322 ('i', _('Instantly')),
325 ('n', _('No notifications')),
328 class SubscriptionSettingsForm(forms.ModelForm):
329 enable_notifications = forms.BooleanField(widget=forms.HiddenInput, required=False)
330 member_joins = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
331 new_question = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
332 new_question_watched_tags = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
333 subscribed_questions = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
336 model = SubscriptionSettings
338 class UserPreferencesForm(forms.Form):
339 sticky_sorts = forms.BooleanField(required=False, initial=False)