2 from datetime import date
3 from django import forms
6 from django.utils.translation import ugettext as _
7 from forum.models import User
8 from django.contrib.contenttypes.models import ContentType
9 from django.utils.safestring import mark_safe
10 from forum.utils.forms import NextUrlField, UserNameField, SetPasswordForm
11 from django.conf import settings
12 from django.contrib.contenttypes.models import ContentType
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_EMPTEY_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. Up to five tags can be used.')
57 def clean(self, value):
58 value = super(TagNamesField, self).clean(value)
61 raise forms.ValidationError(_('tags are required'))
63 split_re = re.compile(r'[ ,]+')
64 list = split_re.split(data)
67 raise forms.ValidationError(_('please use 5 tags or less'))
69 tagname_re = re.compile(r'[a-z0-9]+')
72 raise forms.ValidationError(_('tags must be shorter than 20 characters'))
73 if not tagname_re.match(tag):
74 raise forms.ValidationError(_('please use following characters in tags: letters \'a-z\', numbers, and characters \'.-_#\''))
75 # only keep one same tag
76 if tag not in list_temp and len(tag.strip()) > 0:
78 return u' '.join(list_temp)
80 class WikiField(forms.BooleanField):
81 def __init__(self, *args, **kwargs):
82 super(WikiField, self).__init__(*args, **kwargs)
84 self.label = _('community wiki')
85 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')
86 def clean(self,value):
87 return value and settings.WIKI_ON
89 class EmailNotifyField(forms.BooleanField):
90 def __init__(self, *args, **kwargs):
91 super(EmailNotifyField, self).__init__(*args, **kwargs)
93 self.widget.attrs['class'] = 'nomargin'
95 class SummaryField(forms.CharField):
96 def __init__(self, *args, **kwargs):
97 super(SummaryField, self).__init__(*args, **kwargs)
99 self.widget = forms.TextInput(attrs={'size' : 50, 'autocomplete' : 'off'})
100 self.max_length = 300
101 self.label = _('update summary:')
102 self.help_text = _('enter a brief summary of your revision (e.g. fixed spelling, grammar, improved style, this field is optional)')
105 class FeedbackForm(forms.Form):
106 name = forms.CharField(label=_('Your name:'), required=False)
107 email = forms.EmailField(label=_('Email (not shared with anyone):'), required=False)
108 message = forms.CharField(label=_('Your message:'), max_length=800,widget=forms.Textarea(attrs={'cols':60}))
109 next = NextUrlField()
111 class AskForm(forms.Form):
114 tags = TagNamesField()
118 class AnswerForm(forms.Form):
122 def __init__(self, question, *args, **kwargs):
123 super(AnswerForm, self).__init__(*args, **kwargs)
125 if question.wiki and settings.WIKI_ON:
126 self.fields['wiki'].initial = True
129 class CloseForm(forms.Form):
130 reason = forms.ChoiceField(choices=CLOSE_REASONS)
132 class RetagQuestionForm(forms.Form):
133 tags = TagNamesField()
134 # initialize the default values
135 def __init__(self, question, *args, **kwargs):
136 super(RetagQuestionForm, self).__init__(*args, **kwargs)
137 self.fields['tags'].initial = question.tagnames
139 class RevisionForm(forms.Form):
141 Lists revisions of a Question or Answer
143 revision = forms.ChoiceField(widget=forms.Select(attrs={'style' : 'width:520px'}))
145 def __init__(self, post, *args, **kwargs):
146 super(RevisionForm, self).__init__(*args, **kwargs)
148 revisions = post.revisions.all().values_list(
149 'revision', 'author__username', 'revised_at', 'summary')
151 self.fields['revision'].choices = [
152 (r[0], u'%s - %s (%s) %s' % (r[0], r[1], r[2].strftime(date_format), r[3]))
155 self.fields['revision'].initial = post.active_revision.revision
157 class EditQuestionForm(forms.Form):
160 tags = TagNamesField()
161 summary = SummaryField()
163 def __init__(self, question, revision=None, *args, **kwargs):
164 super(EditQuestionForm, self).__init__(*args, **kwargs)
167 revision = question.active_revision
169 self.fields['title'].initial = revision.title
170 self.fields['text'].initial = revision.body
171 self.fields['tags'].initial = revision.tagnames
173 # Once wiki mode is enabled, it can't be disabled
174 if not question.wiki:
175 self.fields['wiki'] = WikiField()
177 class EditAnswerForm(forms.Form):
179 summary = SummaryField()
181 def __init__(self, answer, revision=None, *args, **kwargs):
182 super(EditAnswerForm, self).__init__(*args, **kwargs)
185 revision = answer.active_revision
187 self.fields['text'].initial = revision.body
189 class EditUserForm(forms.Form):
190 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}))
191 if settings.EDITABLE_SCREEN_NAME:
192 username = UserNameField(label=_('Screen name'))
193 realname = forms.CharField(label=_('Real name'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
194 website = forms.URLField(label=_('Website'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
195 city = forms.CharField(label=_('Location'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
196 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}))
197 about = forms.CharField(label=_('Profile'), required=False, widget=forms.Textarea(attrs={'cols' : 60}))
199 def __init__(self, user, *args, **kwargs):
200 super(EditUserForm, self).__init__(*args, **kwargs)
201 logging.debug('initializing the form')
202 if settings.EDITABLE_SCREEN_NAME:
203 self.fields['username'].initial = user.username
204 self.fields['username'].user_instance = user
205 self.fields['email'].initial = user.email
206 self.fields['realname'].initial = user.real_name
207 self.fields['website'].initial = user.website
208 self.fields['city'].initial = user.location
210 if user.date_of_birth is not None:
211 self.fields['birthday'].initial = user.date_of_birth
213 self.fields['birthday'].initial = '1990-01-01'
214 self.fields['about'].initial = user.about
217 def clean_email(self):
218 """For security reason one unique email in database"""
219 if self.user.email != self.cleaned_data['email']:
220 #todo dry it, there is a similar thing in openidauth
221 if settings.EMAIL_UNIQUE == True:
222 if 'email' in self.cleaned_data:
224 user = User.objects.get(email = self.cleaned_data['email'])
225 except User.DoesNotExist:
226 return self.cleaned_data['email']
227 except User.MultipleObjectsReturned:
228 raise forms.ValidationError(_('this email has already been registered, please use another one'))
229 raise forms.ValidationError(_('this email has already been registered, please use another one'))
230 return self.cleaned_data['email']
233 class SubscriptionSettingsForm(forms.Form):
234 member_joins = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
235 new_question = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
236 new_question_watched_tags = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
237 subscribed_questions = forms.ChoiceField(widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
239 all_questions = forms.BooleanField(required=False, initial=False)
240 all_questions_watched_tags = forms.BooleanField(required=False, initial=False)
241 questions_asked = forms.BooleanField(required=False, initial=False)
242 questions_answered = forms.BooleanField(required=False, initial=False)
243 questions_commented = forms.BooleanField(required=False, initial=False)
244 questions_viewed = forms.BooleanField(required=False, initial=False)
246 notify_answers = forms.BooleanField(required=False, initial=False)
247 notify_reply_to_comments = forms.BooleanField(required=False, initial=False)
248 notify_comments_own_post = forms.BooleanField(required=False, initial=False)
249 notify_comments = forms.BooleanField(required=False, initial=False)
250 notify_accepted = forms.BooleanField(required=False, initial=False)