2 from datetime import date
3 from django import forms
6 from django.utils.translation import ugettext as _
7 from django.contrib.humanize.templatetags.humanize import apnumber
8 from forum.models import User
10 from django.utils.safestring import mark_safe
11 from forum.utils.forms import NextUrlField, UserNameField, SetPasswordForm
12 from django.conf import settings
15 class TitleField(forms.CharField):
16 def __init__(self, *args, **kwargs):
17 super(TitleField, self).__init__(*args, **kwargs)
19 self.widget = forms.TextInput(attrs={'size' : 70, 'autocomplete' : 'off'})
21 self.label = _('title')
22 self.help_text = _('please enter a descriptive title for your question')
25 def clean(self, value):
26 if len(value) < settings.FORM_MIN_QUESTION_TITLE:
27 raise forms.ValidationError(_('title must be must be at least %s characters' % settings.FORM_MIN_QUESTION_TITLE))
31 class EditorField(forms.CharField):
32 def __init__(self, *args, **kwargs):
33 super(EditorField, self).__init__(*args, **kwargs)
35 self.widget = forms.Textarea(attrs={'id':'editor'})
36 self.label = _('content')
40 def clean(self, value):
41 if len(value) < settings.FORM_MIN_QUESTION_BODY and not settings.FORM_EMPTY_QUESTION_BODY:
42 raise forms.ValidationError(_('question content must be must be at least %s characters' % settings.FORM_MIN_QUESTION_BODY))
46 class TagNamesField(forms.CharField):
47 def __init__(self, *args, **kwargs):
48 super(TagNamesField, self).__init__(*args, **kwargs)
50 self.widget = forms.TextInput(attrs={'size' : 50, 'autocomplete' : 'off'})
52 self.label = _('tags')
53 #self.help_text = _('please use space to separate tags (this enables autocomplete feature)')
54 self.help_text = _('Tags are short keywords, with no spaces within. At least one %(min)s and up to %(max)s tags can be used.') % {
55 'min': apnumber(settings.FORM_MIN_NUMBER_OF_TAGS), 'max': apnumber(settings.FORM_MAX_NUMBER_OF_TAGS)
59 def clean(self, value):
60 value = super(TagNamesField, self).clean(value)
63 raise forms.ValidationError(_('tags are required'))
65 split_re = re.compile(r'[ ,]+')
66 list = split_re.split(data)
68 if len(list) > settings.FORM_MAX_NUMBER_OF_TAGS or len(list) < settings.FORM_MIN_NUMBER_OF_TAGS:
69 raise forms.ValidationError(_('please use betwen %(min)s and %(max)s tags') % {
70 'min': apnumber(settings.FORM_MIN_NUMBER_OF_TAGS), 'max': apnumber(settings.FORM_MAX_NUMBER_OF_TAGS)
73 tagname_re = re.compile(r'[a-z0-9]+')
76 raise forms.ValidationError(_('tags must be shorter than 20 characters'))
77 if not tagname_re.match(tag):
78 raise forms.ValidationError(_('please use following characters in tags: letters \'a-z\', numbers, and characters \'.-_#\''))
79 # only keep one same tag
80 if tag not in list_temp and len(tag.strip()) > 0:
82 return u' '.join(list_temp)
84 class WikiField(forms.BooleanField):
85 def __init__(self, *args, **kwargs):
86 super(WikiField, self).__init__(*args, **kwargs)
88 self.label = _('community wiki')
89 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')
90 def clean(self,value):
91 return value and settings.WIKI_ON
93 class EmailNotifyField(forms.BooleanField):
94 def __init__(self, *args, **kwargs):
95 super(EmailNotifyField, self).__init__(*args, **kwargs)
97 self.widget.attrs['class'] = 'nomargin'
99 class SummaryField(forms.CharField):
100 def __init__(self, *args, **kwargs):
101 super(SummaryField, self).__init__(*args, **kwargs)
102 self.required = False
103 self.widget = forms.TextInput(attrs={'size' : 50, 'autocomplete' : 'off'})
104 self.max_length = 300
105 self.label = _('update summary:')
106 self.help_text = _('enter a brief summary of your revision (e.g. fixed spelling, grammar, improved style, this field is optional)')
109 class FeedbackForm(forms.Form):
110 name = forms.CharField(label=_('Your name:'), required=False)
111 email = forms.EmailField(label=_('Email (not shared with anyone):'), required=False)
112 message = forms.CharField(label=_('Your message:'), max_length=800,widget=forms.Textarea(attrs={'cols':60}))
113 next = NextUrlField()
115 class AskForm(forms.Form):
118 tags = TagNamesField()
122 class AnswerForm(forms.Form):
126 def __init__(self, question, *args, **kwargs):
127 super(AnswerForm, self).__init__(*args, **kwargs)
129 if question.wiki and settings.WIKI_ON:
130 self.fields['wiki'].initial = True
133 class CloseForm(forms.Form):
134 reason = forms.ChoiceField(choices=CLOSE_REASONS)
136 class RetagQuestionForm(forms.Form):
137 tags = TagNamesField()
138 # initialize the default values
139 def __init__(self, question, *args, **kwargs):
140 super(RetagQuestionForm, self).__init__(*args, **kwargs)
141 self.fields['tags'].initial = question.tagnames
143 class RevisionForm(forms.Form):
145 Lists revisions of a Question or Answer
147 revision = forms.ChoiceField(widget=forms.Select(attrs={'style' : 'width:520px'}))
149 def __init__(self, post, *args, **kwargs):
150 super(RevisionForm, self).__init__(*args, **kwargs)
152 revisions = post.revisions.all().values_list(
153 'revision', 'author__username', 'revised_at', 'summary')
155 self.fields['revision'].choices = [
156 (r[0], u'%s - %s (%s) %s' % (r[0], r[1], r[2].strftime(date_format), r[3]))
159 self.fields['revision'].initial = post.active_revision.revision
161 class EditQuestionForm(forms.Form):
164 tags = TagNamesField()
165 summary = SummaryField()
167 def __init__(self, question, revision=None, *args, **kwargs):
168 super(EditQuestionForm, self).__init__(*args, **kwargs)
171 revision = question.active_revision
173 self.fields['title'].initial = revision.title
174 self.fields['text'].initial = revision.body
175 self.fields['tags'].initial = revision.tagnames
177 # Once wiki mode is enabled, it can't be disabled
178 if not question.wiki:
179 self.fields['wiki'] = WikiField()
181 class EditAnswerForm(forms.Form):
183 summary = SummaryField()
185 def __init__(self, answer, revision=None, *args, **kwargs):
186 super(EditAnswerForm, self).__init__(*args, **kwargs)
189 revision = answer.active_revision
191 self.fields['text'].initial = revision.body
193 class EditUserForm(forms.Form):
194 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}))
195 if settings.EDITABLE_SCREEN_NAME:
196 username = UserNameField(label=_('Screen name'))
197 realname = forms.CharField(label=_('Real name'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
198 website = forms.URLField(label=_('Website'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
199 city = forms.CharField(label=_('Location'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
200 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}))
201 about = forms.CharField(label=_('Profile'), required=False, widget=forms.Textarea(attrs={'cols' : 60}))
203 def __init__(self, user, *args, **kwargs):
204 super(EditUserForm, self).__init__(*args, **kwargs)
205 logging.debug('initializing the form')
206 if settings.EDITABLE_SCREEN_NAME:
207 self.fields['username'].initial = user.username
208 self.fields['username'].user_instance = user
209 self.fields['email'].initial = user.email
210 self.fields['realname'].initial = user.real_name
211 self.fields['website'].initial = user.website
212 self.fields['city'].initial = user.location
214 if user.date_of_birth is not None:
215 self.fields['birthday'].initial = user.date_of_birth
217 self.fields['birthday'].initial = '1990-01-01'
218 self.fields['about'].initial = user.about
221 def clean_email(self):
222 """For security reason one unique email in database"""
223 if self.user.email != self.cleaned_data['email']:
224 #todo dry it, there is a similar thing in openidauth
225 if settings.EMAIL_UNIQUE == True:
226 if 'email' in self.cleaned_data:
228 user = User.objects.get(email = self.cleaned_data['email'])
229 except User.DoesNotExist:
230 return self.cleaned_data['email']
231 except User.MultipleObjectsReturned:
232 raise forms.ValidationError(_('this email has already been registered, please use another one'))
233 raise forms.ValidationError(_('this email has already been registered, please use another one'))
234 return self.cleaned_data['email']
237 class SubscriptionSettingsForm(forms.Form):
238 member_joins = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
239 new_question = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
240 new_question_watched_tags = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
241 subscribed_questions = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
243 all_questions = forms.BooleanField(required=False, initial=False)
244 all_questions_watched_tags = forms.BooleanField(required=False, initial=False)
245 questions_asked = forms.BooleanField(required=False, initial=False)
246 questions_answered = forms.BooleanField(required=False, initial=False)
247 questions_commented = forms.BooleanField(required=False, initial=False)
248 questions_viewed = forms.BooleanField(required=False, initial=False)
250 notify_answers = forms.BooleanField(required=False, initial=False)
251 notify_reply_to_comments = forms.BooleanField(required=False, initial=False)
252 notify_comments_own_post = forms.BooleanField(required=False, initial=False)
253 notify_comments = forms.BooleanField(required=False, initial=False)
254 notify_accepted = forms.BooleanField(required=False, initial=False)