/
forms.py
314 lines (252 loc) · 12 KB
/
forms.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
import json
import re
from django import forms
from django.conf import settings
from django.template.defaultfilters import slugify
from django.utils.encoding import smart_str
from tower import ugettext_lazy as _lazy
from products.models import Product
from sumo.form_fields import MultiUsernameField, StrippedCharField
from topics.models import Topic
from wiki.config import (GROUPED_FIREFOX_VERSIONS, GROUPED_OPERATING_SYSTEMS,
SIGNIFICANCES, CATEGORIES)
from wiki.models import Document, Revision, MAX_REVISION_COMMENT_LENGTH
from wiki.widgets import (RadioFieldRendererWithHelpText,
TopicsAndSubtopicsWidget)
TITLE_REQUIRED = _lazy(u'Please provide a title.')
TITLE_SHORT = _lazy(u'The title is too short (%(show_value)s characters). '
u'It must be at least %(limit_value)s characters.')
TITLE_LONG = _lazy(u'Please keep the length of the title to %(limit_value)s '
u'characters or less. It is currently %(show_value)s '
u'characters.')
SLUG_REQUIRED = _lazy(u'Please provide a slug.')
SLUG_INVALID = _lazy(u'The slug provided is not valid.')
SLUG_SHORT = _lazy(u'The slug is too short (%(show_value)s characters). '
u'It must be at least %(limit_value)s characters.')
SLUG_LONG = _lazy(u'Please keep the length of the slug to %(limit_value)s '
u'characters or less. It is currently %(show_value)s '
u'characters.')
SUMMARY_REQUIRED = _lazy(u'Please provide a summary.')
SUMMARY_SHORT = _lazy(u'The summary is too short (%(show_value)s characters). '
u'It must be at least %(limit_value)s characters.')
SUMMARY_LONG = _lazy(u'Please keep the length of the summary to '
u'%(limit_value)s characters or less. It is currently '
u'%(show_value)s characters.')
CONTENT_REQUIRED = _lazy(u'Please provide content.')
CONTENT_SHORT = _lazy(u'The content is too short (%(show_value)s characters). '
u'It must be at least %(limit_value)s characters.')
CONTENT_LONG = _lazy(u'Please keep the length of the content to '
u'%(limit_value)s characters or less. It is currently '
u'%(show_value)s characters.')
COMMENT_LONG = _lazy(u'Please keep the length of the comment to '
u'%(limit_value)s characters or less. It is currently '
u'%(show_value)s characters.')
PRODUCT_REQUIRED = _lazy(u'Please select at least one product.')
TOPIC_REQUIRED = _lazy(u'Please select at least one topic.')
class DocumentForm(forms.ModelForm):
"""Form to create/edit a document."""
def __init__(self, *args, **kwargs):
# Quasi-kwargs:
can_archive = kwargs.pop('can_archive', False)
can_edit_needs_change = kwargs.pop('can_edit_needs_change', False)
initial_title = kwargs.pop('initial_title', '')
super(DocumentForm, self).__init__(*args, **kwargs)
title_field = self.fields['title']
title_field.initial = initial_title
slug_field = self.fields['slug']
slug_field.initial = slugify(initial_title)
topics_field = self.fields['topics']
topics_field.choices = Topic.objects.values_list('id', 'title')
products_field = self.fields['products']
products_field.choices = Product.objects.values_list('id', 'title')
# If user hasn't permission to frob is_archived, remove the field. This
# causes save() to skip it as well.
if not can_archive:
del self.fields['is_archived']
# If user hasn't permission to mess with needs_change*, remove the
# fields. This causes save() to skip it as well.
if not can_edit_needs_change:
del self.fields['needs_change']
del self.fields['needs_change_comment']
title = StrippedCharField(
min_length=5, max_length=255,
widget=forms.TextInput(),
label=_lazy(u'Title:'),
help_text=_lazy(u'Title of article'),
error_messages={'required': TITLE_REQUIRED,
'min_length': TITLE_SHORT,
'max_length': TITLE_LONG})
# We don't use forms.SlugField because it is too strict in
# what it allows (English/Roman alpha-numeric characters and dashes).
# Instead, we do custom validation in `clean_slug` below.
slug = StrippedCharField(
min_length=3, max_length=255,
widget=forms.TextInput(),
label=_lazy(u'Slug:'),
help_text=_lazy(u'Article URL'),
error_messages={'required': SLUG_REQUIRED,
'min_length': SLUG_SHORT,
'max_length': SLUG_LONG})
products = forms.MultipleChoiceField(
label=_lazy(u'Relevant to:'),
required=False,
widget=forms.CheckboxSelectMultiple())
is_localizable = forms.BooleanField(
initial=True,
label=_lazy(u'Allow translations:'),
required=False)
is_archived = forms.BooleanField(
label=_lazy(u'Obsolete:'),
required=False)
allow_discussion = forms.BooleanField(
label=_lazy(u'Allow discussion on this article?'),
initial=True,
required=False)
category = forms.ChoiceField(
choices=CATEGORIES,
# Required for non-translations, which is
# enforced in Document.clean().
required=False,
label=_lazy(u'Category:'),
help_text=_lazy(u'Type of article'))
topics = forms.MultipleChoiceField(
label=_lazy(u'Topics:'),
required=False,
widget=TopicsAndSubtopicsWidget())
locale = forms.CharField(widget=forms.HiddenInput())
needs_change = forms.BooleanField(
label=_lazy(u'Needs change:'),
initial=False,
required=False)
needs_change_comment = forms.CharField(
label=_lazy(u'Comment:'),
widget=forms.Textarea(),
required=False)
def clean_slug(self):
slug = self.cleaned_data['slug']
# Blacklist /, ? and +
if not re.compile(r'^[^/^\+^\?]+$').match(slug):
raise forms.ValidationError(SLUG_INVALID)
return slug
def clean(self):
c = super(DocumentForm, self).clean()
locale = c.get('locale')
# Products are required for en-US
products = c.get('products')
if (locale == settings.WIKI_DEFAULT_LANGUAGE and
(not products or len(products) < 1)):
raise forms.ValidationError(PRODUCT_REQUIRED)
# Topics are required for en-US
topics = c.get('topics')
if (locale == settings.WIKI_DEFAULT_LANGUAGE and
(not topics or len(topics) < 1)):
raise forms.ValidationError(TOPIC_REQUIRED)
return c
class Meta:
model = Document
fields = ('title', 'slug', 'category', 'is_localizable', 'products',
'topics', 'locale', 'is_archived', 'allow_discussion',
'needs_change', 'needs_change_comment')
def save(self, parent_doc, **kwargs):
"""Persist the Document form, and return the saved Document."""
doc = super(DocumentForm, self).save(commit=False, **kwargs)
doc.parent = parent_doc
# If document doesn't need change, clear out the comment.
if not doc.needs_change:
doc.needs_change_comment = ''
doc.save()
self.save_m2m()
if parent_doc:
# Products are not set on translations.
doc.products.remove(*[p for p in doc.products.all()])
return doc
class RevisionForm(forms.ModelForm):
"""Form to create new revisions."""
keywords = StrippedCharField(required=False,
label=_lazy(u'Keywords:'),
help_text=_lazy(u'Affects search results'))
summary = StrippedCharField(
min_length=5, max_length=1000, widget=forms.Textarea(),
label=_lazy(u'Search result summary:'),
help_text=_lazy(u'Only displayed on search results page'),
error_messages={'required': SUMMARY_REQUIRED,
'min_length': SUMMARY_SHORT,
'max_length': SUMMARY_LONG})
showfor_data = {
'oses': [(smart_str(c[0][0]), [(o.slug, smart_str(o.name)) for
o in c[1]]) for
c in GROUPED_OPERATING_SYSTEMS],
'versions': [(smart_str(c[0][0]), [(v.slug, smart_str(v.name)) for
v in c[1] if v.show_in_ui]) for
c in GROUPED_FIREFOX_VERSIONS]}
content = StrippedCharField(
min_length=5, max_length=100000,
label=_lazy(u'Content:'),
widget=forms.Textarea(attrs={'data-showfor':
json.dumps(showfor_data)}),
error_messages={'required': CONTENT_REQUIRED,
'min_length': CONTENT_SHORT,
'max_length': CONTENT_LONG})
comment = StrippedCharField(required=False, label=_lazy(u'Comment:'))
class Meta(object):
model = Revision
fields = ('keywords', 'summary', 'content', 'comment', 'based_on')
def __init__(self, *args, **kwargs):
super(RevisionForm, self).__init__(*args, **kwargs)
self.fields['based_on'].widget = forms.HiddenInput()
self.fields['comment'].widget = forms.TextInput(
attrs={'maxlength': MAX_REVISION_COMMENT_LENGTH})
def save(self, creator, document, based_on_id=None, base_rev=None,
**kwargs):
"""Persist me, and return the saved Revision.
Take several other necessary pieces of data that aren't from the
form.
"""
# Throws a TypeError if somebody passes in a commit kwarg:
new_rev = super(RevisionForm, self).save(commit=False, **kwargs)
new_rev.document = document
new_rev.creator = creator
if based_on_id:
new_rev.based_on_id = based_on_id
# If the document doesn't allow the revision creator to edit the
# keywords, keep the old value.
if base_rev and not document.allows(creator, 'edit_keywords'):
new_rev.keywords = base_rev.keywords
new_rev.save()
return new_rev
class ReviewForm(forms.Form):
comment = StrippedCharField(max_length=2000, widget=forms.Textarea(),
required=False, label=_lazy(u'Comment:'),
error_messages={'max_length': COMMENT_LONG})
_widget = forms.RadioSelect(renderer=RadioFieldRendererWithHelpText)
significance = forms.ChoiceField(
label=_lazy(u'Significance:'),
choices=SIGNIFICANCES,
initial=SIGNIFICANCES[1][0],
required=False, widget=_widget)
is_ready_for_localization = forms.BooleanField(
initial=False,
label=_lazy(u'Ready for localization'),
required=False)
needs_change = forms.BooleanField(
label=_lazy(u'Needs change'),
initial=False,
required=False)
needs_change_comment = forms.CharField(
label=_lazy(u'Comment:'),
widget=forms.Textarea(),
required=False)
class AddContributorForm(forms.Form):
"""Form to add contributors to a document."""
users = MultiUsernameField(
widget=forms.TextInput(attrs={'placeholder': _lazy(u'username'),
'class': 'user-autocomplete'}))
languages = [('', 'Any')] + [(l[0], u'{1} ({0})'.format(*l))
for l in settings.LANGUAGE_CHOICES]
class RevisionFilterForm(forms.Form):
"""Form to filter a list of revisions."""
locale = forms.ChoiceField(label=_lazy(u'Locale:'), choices=languages,
required=False)
users = MultiUsernameField(label=_lazy(u'Users:'), required=False)
start = forms.DateField(label=_lazy(u'Start:'), required=False)
end = forms.DateField(label=_lazy(u'End:'), required=False)