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
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)
163 class AskForm(forms.Form):
165 text = QuestionEditorField()
167 def __init__(self, data=None, user=None, *args, **kwargs):
168 super(AskForm, self).__init__(data, *args, **kwargs)
170 self.fields['tags'] = TagNamesField(user)
172 if int(user.reputation) < settings.CAPTCHA_IF_REP_LESS_THAN and not (user.is_superuser or user.is_staff):
173 spam_fields = call_all_handlers('create_anti_spam_field')
175 spam_fields = dict(spam_fields)
176 for name, field in spam_fields.items():
177 self.fields[name] = field
179 self._anti_spam_fields = spam_fields.keys()
181 self._anti_spam_fields = []
184 self.fields['wiki'] = WikiField()
186 class AnswerForm(forms.Form):
187 text = AnswerEditorField()
190 def __init__(self, data=None, user=None, *args, **kwargs):
191 super(AnswerForm, self).__init__(data, *args, **kwargs)
193 if int(user.reputation) < settings.CAPTCHA_IF_REP_LESS_THAN and not (user.is_superuser or user.is_staff):
194 spam_fields = call_all_handlers('create_anti_spam_field')
196 spam_fields = dict(spam_fields)
197 for name, field in spam_fields.items():
198 self.fields[name] = field
200 self._anti_spam_fields = spam_fields.keys()
202 self._anti_spam_fields = []
205 self.fields['wiki'] = WikiField()
207 class RetagQuestionForm(forms.Form):
208 tags = TagNamesField()
209 # initialize the default values
210 def __init__(self, question, *args, **kwargs):
211 super(RetagQuestionForm, self).__init__(*args, **kwargs)
212 self.fields['tags'].initial = question.tagnames
214 class RevisionForm(forms.Form):
216 Lists revisions of a Question or Answer
218 revision = forms.ChoiceField(widget=forms.Select(attrs={'style' : 'width:520px'}))
220 def __init__(self, post, *args, **kwargs):
221 super(RevisionForm, self).__init__(*args, **kwargs)
223 revisions = post.revisions.all().values_list('revision', 'author__username', 'revised_at', 'summary').order_by('-revised_at')
226 self.fields['revision'].choices = [
227 (r[0], u'%s - %s (%s) %s' % (r[0], smart_unicode(r[1]), r[2].strftime(date_format), r[3]))
230 self.fields['revision'].initial = post.active_revision.revision
232 class EditQuestionForm(forms.Form):
234 text = QuestionEditorField()
235 summary = SummaryField()
237 def __init__(self, question, user, revision=None, *args, **kwargs):
238 super(EditQuestionForm, self).__init__(*args, **kwargs)
241 revision = question.active_revision
243 self.fields['title'].initial = revision.title
244 self.fields['text'].initial = revision.body
246 self.fields['tags'] = TagNamesField(user)
247 self.fields['tags'].initial = revision.tagnames
249 if int(user.reputation) < settings.CAPTCHA_IF_REP_LESS_THAN and not (user.is_superuser or user.is_staff):
250 spam_fields = call_all_handlers('create_anti_spam_field')
252 spam_fields = dict(spam_fields)
253 for name, field in spam_fields.items():
254 self.fields[name] = field
256 self._anti_spam_fields = spam_fields.keys()
258 self._anti_spam_fields = []
261 self.fields['wiki'] = WikiField(disabled=(question.nis.wiki and not user.can_cancel_wiki(question)), initial=question.nis.wiki)
263 class EditAnswerForm(forms.Form):
264 text = AnswerEditorField()
265 summary = SummaryField()
267 def __init__(self, answer, user, revision=None, *args, **kwargs):
268 super(EditAnswerForm, self).__init__(*args, **kwargs)
271 revision = answer.active_revision
273 self.fields['text'].initial = revision.body
275 if int(user.reputation) < settings.CAPTCHA_IF_REP_LESS_THAN and not (user.is_superuser or user.is_staff):
276 spam_fields = call_all_handlers('create_anti_spam_field')
278 spam_fields = dict(spam_fields)
279 for name, field in spam_fields.items():
280 self.fields[name] = field
282 self._anti_spam_fields = spam_fields.keys()
284 self._anti_spam_fields = []
287 self.fields['wiki'] = WikiField(disabled=(answer.nis.wiki and not user.can_cancel_wiki(answer)), initial=answer.nis.wiki)
289 class EditUserForm(forms.Form):
290 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}))
291 realname = forms.CharField(label=_('Real name'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
292 website = forms.URLField(label=_('Website'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
293 city = forms.CharField(label=_('Location'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
294 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}))
295 about = forms.CharField(label=_('Profile'), required=False, widget=forms.Textarea(attrs={'cols' : 60}))
297 def __init__(self, user, *args, **kwargs):
298 super(EditUserForm, self).__init__(*args, **kwargs)
299 if settings.EDITABLE_SCREEN_NAME:
300 self.fields['username'] = UserNameField(label=_('Screen name'))
301 self.fields['username'].initial = user.username
302 self.fields['username'].user_instance = user
303 self.fields['email'].initial = user.email
304 self.fields['realname'].initial = user.real_name
305 self.fields['website'].initial = user.website
306 self.fields['city'].initial = user.location
308 if user.date_of_birth is not None:
309 self.fields['birthday'].initial = user.date_of_birth
311 self.fields['about'].initial = user.about
314 def clean_email(self):
315 if self.user.email != self.cleaned_data['email']:
316 if settings.EMAIL_UNIQUE:
317 if 'email' in self.cleaned_data:
318 from forum.models import User
320 User.objects.get(email = self.cleaned_data['email'])
321 except User.DoesNotExist:
322 return self.cleaned_data['email']
323 except User.MultipleObjectsReturned:
324 logging.error("Found multiple users sharing the same email: %s" % self.cleaned_data['email'])
326 raise forms.ValidationError(_('this email has already been registered, please use another one'))
327 return self.cleaned_data['email']
330 NOTIFICATION_CHOICES = (
331 ('i', _('Instantly')),
334 ('n', _('No notifications')),
337 class SubscriptionSettingsForm(forms.ModelForm):
338 enable_notifications = forms.BooleanField(widget=forms.HiddenInput, required=False)
339 member_joins = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
340 new_question = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
341 new_question_watched_tags = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
342 subscribed_questions = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
345 model = SubscriptionSettings
347 class UserPreferencesForm(forms.Form):
348 sticky_sorts = forms.BooleanField(required=False, initial=False)