2 from datetime import date
3 from django import forms
5 from django.utils.translation import ugettext as _
6 from django.contrib.humanize.templatetags.humanize import apnumber
7 from forum.models import User
9 from django.utils.safestring import mark_safe
10 from forum.utils.forms import NextUrlField, UserNameField, SetPasswordForm
11 from forum import settings
14 class TitleField(forms.CharField):
15 def __init__(self, *args, **kwargs):
16 super(TitleField, self).__init__(*args, **kwargs)
18 self.widget = forms.TextInput(attrs={'size' : 70, 'autocomplete' : 'off'})
20 self.label = _('title')
21 self.help_text = _('please enter a descriptive title for your question')
24 def clean(self, value):
25 if len(value) < settings.FORM_MIN_QUESTION_TITLE:
26 raise forms.ValidationError(_('title must be must be at least %s characters' % settings.FORM_MIN_QUESTION_TITLE))
30 class EditorField(forms.CharField):
31 def __init__(self, *args, **kwargs):
32 super(EditorField, self).__init__(*args, **kwargs)
33 self.widget = forms.Textarea(attrs={'id':'editor'})
34 self.label = _('content')
39 class QuestionEditorField(EditorField):
40 def __init__(self, *args, **kwargs):
41 super(QuestionEditorField, self).__init__(*args, **kwargs)
42 self.required = not bool(settings.FORM_EMPTY_QUESTION_BODY)
45 def clean(self, value):
46 if self.required and (len(value) < settings.FORM_MIN_QUESTION_BODY):
47 raise forms.ValidationError(_('question content must be must be at least %s characters' % settings.FORM_MIN_QUESTION_BODY))
51 class AnswerEditorField(EditorField):
52 def __init__(self, *args, **kwargs):
53 super(AnswerEditorField, self).__init__(*args, **kwargs)
56 def clean(self, value):
57 if len(value) < settings.FORM_MIN_QUESTION_BODY:
58 raise forms.ValidationError(_('answer content must be must be at least %s characters' % settings.FORM_MIN_QUESTION_BODY))
63 class TagNamesField(forms.CharField):
64 def __init__(self, *args, **kwargs):
65 super(TagNamesField, self).__init__(*args, **kwargs)
67 self.widget = forms.TextInput(attrs={'size' : 50, 'autocomplete' : 'off'})
69 self.label = _('tags')
70 #self.help_text = _('please use space to separate tags (this enables autocomplete feature)')
71 self.help_text = _('Tags are short keywords, with no spaces within. At least %(min)s and up to %(max)s tags can be used.') % {
72 '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'[ ,]+')
81 list = split_re.split(data)
83 if len(list) > settings.FORM_MAX_NUMBER_OF_TAGS or len(list) < settings.FORM_MIN_NUMBER_OF_TAGS:
84 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})
87 tagname_re = re.compile(r'^[\w+\.-]+$', re.UNICODE)
89 if len(tag) > settings.FORM_MAX_LENGTH_OF_TAG or len(tag) < settings.FORM_MIN_LENGTH_OF_TAG:
90 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})
91 if not tagname_re.match(tag):
92 raise forms.ValidationError(_('please use following characters in tags: letters , numbers, and characters \'.-_\''))
93 # only keep one same tag
94 if tag not in list_temp and len(tag.strip()) > 0:
97 return u' '.join(list_temp)
99 class WikiField(forms.BooleanField):
100 def __init__(self, *args, **kwargs):
101 super(WikiField, self).__init__(*args, **kwargs)
102 self.required = False
103 self.label = _('community wiki')
104 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')
105 def clean(self,value):
106 return value and settings.WIKI_ON
108 class EmailNotifyField(forms.BooleanField):
109 def __init__(self, *args, **kwargs):
110 super(EmailNotifyField, self).__init__(*args, **kwargs)
111 self.required = False
112 self.widget.attrs['class'] = 'nomargin'
114 class SummaryField(forms.CharField):
115 def __init__(self, *args, **kwargs):
116 super(SummaryField, self).__init__(*args, **kwargs)
117 self.required = False
118 self.widget = forms.TextInput(attrs={'size' : 50, 'autocomplete' : 'off'})
119 self.max_length = 300
120 self.label = _('update summary:')
121 self.help_text = _('enter a brief summary of your revision (e.g. fixed spelling, grammar, improved style, this field is optional)')
124 class FeedbackForm(forms.Form):
125 name = forms.CharField(label=_('Your name:'), required=False)
126 email = forms.EmailField(label=_('Email (not shared with anyone):'), required=False)
127 message = forms.CharField(label=_('Your message:'), max_length=800,widget=forms.Textarea(attrs={'cols':60}))
128 next = NextUrlField()
130 class AskForm(forms.Form):
132 text = QuestionEditorField()
133 tags = TagNamesField()
137 class AnswerForm(forms.Form):
138 text = AnswerEditorField()
141 def __init__(self, question, *args, **kwargs):
142 super(AnswerForm, self).__init__(*args, **kwargs)
144 if question.wiki and settings.WIKI_ON:
145 self.fields['wiki'].initial = True
148 class RetagQuestionForm(forms.Form):
149 tags = TagNamesField()
150 # initialize the default values
151 def __init__(self, question, *args, **kwargs):
152 super(RetagQuestionForm, self).__init__(*args, **kwargs)
153 self.fields['tags'].initial = question.tagnames
155 class RevisionForm(forms.Form):
157 Lists revisions of a Question or Answer
159 revision = forms.ChoiceField(widget=forms.Select(attrs={'style' : 'width:520px'}))
161 def __init__(self, post, *args, **kwargs):
162 super(RevisionForm, self).__init__(*args, **kwargs)
164 revisions = post.revisions.all().values_list(
165 'revision', 'author__username', 'revised_at', 'summary')
167 self.fields['revision'].choices = [
168 (r[0], u'%s - %s (%s) %s' % (r[0], r[1], r[2].strftime(date_format), r[3]))
171 self.fields['revision'].initial = post.active_revision.revision
173 class EditQuestionForm(forms.Form):
175 text = QuestionEditorField()
176 tags = TagNamesField()
177 summary = SummaryField()
179 def __init__(self, question, revision=None, *args, **kwargs):
180 super(EditQuestionForm, self).__init__(*args, **kwargs)
183 revision = question.active_revision
185 self.fields['title'].initial = revision.title
186 self.fields['text'].initial = revision.body
187 self.fields['tags'].initial = revision.tagnames
189 # Once wiki mode is enabled, it can't be disabled
190 if not question.wiki:
191 self.fields['wiki'] = WikiField()
193 class EditAnswerForm(forms.Form):
194 text = AnswerEditorField()
195 summary = SummaryField()
197 def __init__(self, answer, revision=None, *args, **kwargs):
198 super(EditAnswerForm, self).__init__(*args, **kwargs)
201 revision = answer.active_revision
203 self.fields['text'].initial = revision.body
205 class EditUserForm(forms.Form):
206 email = forms.EmailField(label=u'Email', help_text=_('this email does not have to be linked to gravatar'), required=True, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
207 realname = forms.CharField(label=_('Real name'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
208 website = forms.URLField(label=_('Website'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
209 city = forms.CharField(label=_('Location'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
210 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}))
211 about = forms.CharField(label=_('Profile'), required=False, widget=forms.Textarea(attrs={'cols' : 60}))
213 def __init__(self, user, *args, **kwargs):
214 super(EditUserForm, self).__init__(*args, **kwargs)
215 if settings.EDITABLE_SCREEN_NAME:
216 self.fields['username'] = UserNameField(label=_('Screen name'))
217 self.fields['username'].initial = user.username
218 self.fields['username'].user_instance = user
219 self.fields['email'].initial = user.email
220 self.fields['realname'].initial = user.real_name
221 self.fields['website'].initial = user.website
222 self.fields['city'].initial = user.location
224 if user.date_of_birth is not None:
225 self.fields['birthday'].initial = user.date_of_birth
227 self.fields['birthday'].initial = '1990-01-01'
228 self.fields['about'].initial = user.about
231 def clean_email(self):
232 """For security reason one unique email in database"""
233 if self.user.email != self.cleaned_data['email']:
234 #todo dry it, there is a similar thing in openidauth
235 if settings.EMAIL_UNIQUE == True:
236 if 'email' in self.cleaned_data:
238 user = User.objects.get(email = self.cleaned_data['email'])
239 except User.DoesNotExist:
240 return self.cleaned_data['email']
241 except User.MultipleObjectsReturned:
242 raise forms.ValidationError(_('this email has already been registered, please use another one'))
243 raise forms.ValidationError(_('this email has already been registered, please use another one'))
244 return self.cleaned_data['email']
246 NOTIFICATION_CHOICES = (
247 ('i', _('Instantly')),
250 ('n', _('No notifications')),
253 class SubscriptionSettingsForm(forms.Form):
254 member_joins = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
255 new_question = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
256 new_question_watched_tags = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
257 subscribed_questions = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
259 all_questions = forms.BooleanField(required=False, initial=False)
260 all_questions_watched_tags = forms.BooleanField(required=False, initial=False)
261 questions_asked = forms.BooleanField(required=False, initial=False)
262 questions_answered = forms.BooleanField(required=False, initial=False)
263 questions_commented = forms.BooleanField(required=False, initial=False)
264 questions_viewed = forms.BooleanField(required=False, initial=False)
266 notify_answers = forms.BooleanField(required=False, initial=False)
267 notify_reply_to_comments = forms.BooleanField(required=False, initial=False)
268 notify_comments_own_post = forms.BooleanField(required=False, initial=False)
269 notify_comments = forms.BooleanField(required=False, initial=False)
270 notify_accepted = forms.BooleanField(required=False, initial=False)