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
13 class TitleField(forms.CharField):
14 def __init__(self, *args, **kwargs):
15 super(TitleField, self).__init__(*args, **kwargs)
17 self.widget = forms.TextInput(attrs={'size' : 70, 'autocomplete' : 'off'})
19 self.label = _('title')
20 self.help_text = _('please enter a descriptive title for your question')
23 def clean(self, value):
24 if len(value) < settings.FORM_MIN_QUESTION_TITLE:
25 raise forms.ValidationError(_('title must be must be at least %s characters') % settings.FORM_MIN_QUESTION_TITLE)
29 class EditorField(forms.CharField):
30 def __init__(self, *args, **kwargs):
31 super(EditorField, self).__init__(*args, **kwargs)
32 self.widget = forms.Textarea(attrs={'id':'editor'})
33 self.label = _('content')
38 class QuestionEditorField(EditorField):
39 def __init__(self, *args, **kwargs):
40 super(QuestionEditorField, self).__init__(*args, **kwargs)
41 self.required = not bool(settings.FORM_EMPTY_QUESTION_BODY)
44 def clean(self, value):
45 if self.required and (len(re.sub('[ ]{2,}', ' ', value)) < settings.FORM_MIN_QUESTION_BODY):
46 raise forms.ValidationError(_('question content must be at least %s characters') % settings.FORM_MIN_QUESTION_BODY)
50 class AnswerEditorField(EditorField):
51 def __init__(self, *args, **kwargs):
52 super(AnswerEditorField, self).__init__(*args, **kwargs)
55 def clean(self, value):
56 if len(re.sub('[ ]{2,}', ' ', value)) < settings.FORM_MIN_QUESTION_BODY:
57 raise forms.ValidationError(_('answer content must be at least %s characters') % settings.FORM_MIN_QUESTION_BODY)
62 class TagNamesField(forms.CharField):
63 def __init__(self, user=None, *args, **kwargs):
64 super(TagNamesField, self).__init__(*args, **kwargs)
66 self.widget = forms.TextInput(attrs={'size' : 50, 'autocomplete' : 'off'})
68 self.label = _('tags')
69 #self.help_text = _('please use space to separate tags (this enables autocomplete feature)')
70 self.help_text = _('Tags are short keywords, with no spaces within. At least %(min)s and up to %(max)s tags can be used.') % {
71 'min': settings.FORM_MIN_NUMBER_OF_TAGS, 'max': settings.FORM_MAX_NUMBER_OF_TAGS
76 def clean(self, value):
77 value = super(TagNamesField, self).clean(value)
78 data = value.strip().lower()
80 split_re = re.compile(r'[ ,]+')
82 for tag in split_re.split(data):
85 if len(list) > settings.FORM_MAX_NUMBER_OF_TAGS or len(list) < settings.FORM_MIN_NUMBER_OF_TAGS:
86 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})
89 tagname_re = re.compile(r'^[\w+\.-]+$', re.UNICODE)
91 if len(tag) > settings.FORM_MAX_LENGTH_OF_TAG or len(tag) < settings.FORM_MIN_LENGTH_OF_TAG:
92 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})
93 if not tagname_re.match(tag):
94 raise forms.ValidationError(_('please use following characters in tags: letters , numbers, and characters \'.-_\''))
95 # only keep one same tag
96 if tag not in list_temp and len(tag.strip()) > 0:
99 if settings.LIMIT_TAG_CREATION and not self.user.can_create_tags():
100 existent = Tag.objects.filter(name__in=list_temp).values_list('name', flat=True)
102 if len(existent) < len(list_temp):
103 unexistent = [n for n in list_temp if not n in existent]
104 raise forms.ValidationError(_("You don't have enough reputation to create new tags. The following tags do not exist yet: %s") %
105 ', '.join(unexistent))
108 return u' '.join(list_temp)
110 class WikiField(forms.BooleanField):
111 def __init__(self, disabled=False, *args, **kwargs):
112 super(WikiField, self).__init__(*args, **kwargs)
113 self.required = False
114 self.label = _('community wiki')
115 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')
117 self.widget=forms.CheckboxInput(attrs={'disabled': "disabled"})
118 def clean(self,value):
121 class EmailNotifyField(forms.BooleanField):
122 def __init__(self, *args, **kwargs):
123 super(EmailNotifyField, self).__init__(*args, **kwargs)
124 self.required = False
125 self.widget.attrs['class'] = 'nomargin'
127 class SummaryField(forms.CharField):
128 def __init__(self, *args, **kwargs):
129 super(SummaryField, self).__init__(*args, **kwargs)
130 self.required = False
131 self.widget = forms.TextInput(attrs={'size' : 50, 'autocomplete' : 'off'})
132 self.max_length = 300
133 self.label = _('update summary:')
134 self.help_text = _('enter a brief summary of your revision (e.g. fixed spelling, grammar, improved style, this field is optional)')
137 class FeedbackForm(forms.Form):
138 name = forms.CharField(label=_('Your name:'), required=False)
139 email = forms.EmailField(label=_('Email (not shared with anyone):'), required=False)
140 message = forms.CharField(label=_('Your message:'), max_length=800,widget=forms.Textarea(attrs={'cols':60}))
141 next = NextUrlField()
143 class AskForm(forms.Form):
145 text = QuestionEditorField()
147 def __init__(self, data=None, user=None, *args, **kwargs):
148 super(AskForm, self).__init__(data, *args, **kwargs)
150 self.fields['tags'] = TagNamesField(user)
153 self.fields['wiki'] = WikiField()
155 class AnswerForm(forms.Form):
156 text = AnswerEditorField()
159 def __init__(self, question, *args, **kwargs):
160 super(AnswerForm, self).__init__(*args, **kwargs)
163 self.fields['wiki'] = WikiField()
165 if question.nis.wiki:
166 self.fields['wiki'].initial = True
169 class RetagQuestionForm(forms.Form):
170 tags = TagNamesField()
171 # initialize the default values
172 def __init__(self, question, *args, **kwargs):
173 super(RetagQuestionForm, self).__init__(*args, **kwargs)
174 self.fields['tags'].initial = question.tagnames
176 class RevisionForm(forms.Form):
178 Lists revisions of a Question or Answer
180 revision = forms.ChoiceField(widget=forms.Select(attrs={'style' : 'width:520px'}))
182 def __init__(self, post, *args, **kwargs):
183 super(RevisionForm, self).__init__(*args, **kwargs)
185 revisions = post.revisions.all().values_list(
186 'revision', 'author__username', 'revised_at', 'summary')
188 self.fields['revision'].choices = [
189 (r[0], u'%s - %s (%s) %s' % (r[0], r[1], r[2].strftime(date_format), r[3]))
192 self.fields['revision'].initial = post.active_revision.revision
194 class EditQuestionForm(forms.Form):
196 text = QuestionEditorField()
197 summary = SummaryField()
199 def __init__(self, question, user, revision=None, *args, **kwargs):
200 super(EditQuestionForm, self).__init__(*args, **kwargs)
203 revision = question.active_revision
205 self.fields['title'].initial = revision.title
206 self.fields['text'].initial = revision.body
208 self.fields['tags'] = TagNamesField(user)
209 self.fields['tags'].initial = revision.tagnames
212 self.fields['wiki'] = WikiField(disabled=(question.nis.wiki and not user.can_cancel_wiki(question)), initial=question.nis.wiki)
214 class EditAnswerForm(forms.Form):
215 text = AnswerEditorField()
216 summary = SummaryField()
218 def __init__(self, answer, user, revision=None, *args, **kwargs):
219 super(EditAnswerForm, self).__init__(*args, **kwargs)
222 revision = answer.active_revision
224 self.fields['text'].initial = revision.body
227 self.fields['wiki'] = WikiField(disabled=(answer.nis.wiki and not user.can_cancel_wiki(answer)), initial=answer.nis.wiki)
229 class EditUserForm(forms.Form):
230 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}))
231 realname = forms.CharField(label=_('Real name'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
232 website = forms.URLField(label=_('Website'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
233 city = forms.CharField(label=_('Location'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
234 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}))
235 about = forms.CharField(label=_('Profile'), required=False, widget=forms.Textarea(attrs={'cols' : 60}))
237 def __init__(self, user, *args, **kwargs):
238 super(EditUserForm, self).__init__(*args, **kwargs)
239 if settings.EDITABLE_SCREEN_NAME:
240 self.fields['username'] = UserNameField(label=_('Screen name'))
241 self.fields['username'].initial = user.username
242 self.fields['username'].user_instance = user
243 self.fields['email'].initial = user.email
244 self.fields['realname'].initial = user.real_name
245 self.fields['website'].initial = user.website
246 self.fields['city'].initial = user.location
248 if user.date_of_birth is not None:
249 self.fields['birthday'].initial = user.date_of_birth
251 self.fields['birthday'].initial = '1990-01-01'
252 self.fields['about'].initial = user.about
255 def clean_email(self):
256 if self.user.email != self.cleaned_data['email']:
257 if settings.EMAIL_UNIQUE == True:
258 if 'email' in self.cleaned_data:
259 from forum.models import User
261 User.objects.get(email = self.cleaned_data['email'])
262 except User.DoesNotExist:
263 return self.cleaned_data['email']
264 except User.MultipleObjectsReturned:
265 logging.error("Found multiple users sharing the same email: %s" % self.cleaned_data['email'])
267 raise forms.ValidationError(_('this email has already been registered, please use another one'))
268 return self.cleaned_data['email']
270 NOTIFICATION_CHOICES = (
271 ('i', _('Instantly')),
274 ('n', _('No notifications')),
277 class SubscriptionSettingsForm(forms.Form):
278 member_joins = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
279 new_question = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
280 new_question_watched_tags = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
281 subscribed_questions = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
283 all_questions = forms.BooleanField(required=False, initial=False)
284 all_questions_watched_tags = forms.BooleanField(required=False, initial=False)
285 questions_asked = forms.BooleanField(required=False, initial=False)
286 questions_answered = forms.BooleanField(required=False, initial=False)
287 questions_commented = forms.BooleanField(required=False, initial=False)
288 questions_viewed = forms.BooleanField(required=False, initial=False)
290 notify_answers = forms.BooleanField(required=False, initial=False)
291 notify_reply_to_comments = forms.BooleanField(required=False, initial=False)
292 notify_comments_own_post = forms.BooleanField(required=False, initial=False)
293 notify_comments = forms.BooleanField(required=False, initial=False)
294 notify_accepted = forms.BooleanField(required=False, initial=False)