forked from ASKBOT/askbot-devel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathforms.py
1744 lines (1459 loc) · 62.4 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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Forms, custom form fields and related utility functions
used in AskBot"""
import re
import datetime
from django import forms
from askbot import const
from askbot.const import message_keys
from django.conf import settings as django_settings
from django.core.exceptions import PermissionDenied
from django.forms.util import ErrorList
from django.utils.html import strip_tags
from django.utils.datastructures import SortedDict
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import ungettext_lazy, string_concat
from django.utils.translation import get_language
from django.utils.text import get_text_list
from django.contrib.auth.models import User
from django_countries import countries
from askbot.utils.forms import NextUrlField, UserNameField
from askbot.mail import extract_first_email_address
from recaptcha_works.fields import RecaptchaField
from askbot.conf import settings as askbot_settings
from askbot.conf import get_tag_display_filter_strategy_choices
from tinymce.widgets import TinyMCE
import logging
def should_use_recaptcha(user):
"""True if user must use recaptcha"""
return askbot_settings.USE_RECAPTCHA and (user.is_anonymous() or user.is_watched())
def cleanup_dict(dictionary, key, empty_value):
"""deletes key from dictionary if it exists
and the corresponding value equals the empty_value
"""
if key in dictionary and dictionary[key] == empty_value:
del dictionary[key]
def format_form_errors(form):
"""Formats form errors in HTML
if there is only one error - returns a plain string
if more than one, returns an unordered list of errors
in HTML format.
If there are no errors, returns empty string
"""
if form.errors:
errors = form.errors.values()
if len(errors) == 1:
return errors[0]
else:
result = '<ul>'
for error in errors:
result += '<li>%s</li>' % error
result += '</ul>'
return result
else:
return ''
def clean_marked_tagnames(tagnames):
"""return two strings - one containing tagnames
that are straight names of tags, and the second one
containing names of wildcard tags,
wildcard tags are those that have an asterisk at the end
the function does not verify that the tag names are valid
"""
if askbot_settings.USE_WILDCARD_TAGS is False:
return tagnames, list()
pure_tags = list()
wildcards = list()
for tagname in tagnames:
if tagname == '':
continue
if tagname.endswith('*'):
if tagname.count('*') > 1 or len(tagname) == 1:
continue
else:
base_tag = tagname[:-1]
cleaned_base_tag = clean_tag(base_tag, look_in_db=False)
wildcards.append(cleaned_base_tag + '*')
else:
pure_tags.append(clean_tag(tagname))
return pure_tags, wildcards
def filter_choices(remove_choices=None, from_choices=None):
"""a utility function that will remove choice tuples
usable for the forms.ChoicesField from
``from_choices``, the removed ones will be those given
by the ``remove_choice`` list
there is no error checking, ``from_choices`` tuple must be as expected
to work with the forms.ChoicesField
"""
if not isinstance(remove_choices, list):
raise TypeError('remove_choices must be a list')
filtered_choices = tuple()
for choice_to_test in from_choices:
remove = False
for choice in remove_choices:
if choice == choice_to_test[0]:
remove = True
break
if remove is False:
filtered_choices += (choice_to_test, )
return filtered_choices
def need_mandatory_tags():
"""true, if list of mandatory tags is not empty"""
from askbot import models
return (
askbot_settings.TAGS_ARE_REQUIRED
and len(models.tag.get_mandatory_tags()) > 0
)
def mandatory_tag_missing_in_list(tag_strings):
"""true, if mandatory tag is not present in the list
of ``tag_strings``"""
from askbot import models
mandatory_tags = models.tag.get_mandatory_tags()
for mandatory_tag in mandatory_tags:
for tag_string in tag_strings:
if tag_strings_match(tag_string, mandatory_tag):
return False
return True
def tag_strings_match(tag_string, mandatory_tag):
"""true if tag string matches the mandatory tag,
the comparison is not symmetric if tag_string ends with a
wildcard (asterisk)
"""
if mandatory_tag.endswith('*'):
return tag_string.startswith(mandatory_tag[:-1])
else:
return tag_string == mandatory_tag
class CountryField(forms.ChoiceField):
"""this is better placed into the django_coutries app"""
def __init__(self, *args, **kwargs):
"""sets label and the country choices
"""
try:
country_choices = countries.COUNTRIES
except AttributeError:
from django_countries import data
country_choices = list()
for key, name in data.COUNTRIES.items():
country_choices.append((key, name))
country_choices = sorted(country_choices, cmp=lambda a,b: cmp(a[1], b[1]))
country_choices = (('unknown', _('select country')),) + tuple(country_choices)
kwargs['choices'] = kwargs.pop('choices', country_choices)
kwargs['label'] = kwargs.pop('label', _('Country'))
super(CountryField, self).__init__(*args, **kwargs)
def clean(self, value):
"""Handles case of 'unknown' country selection
"""
if self.required:
if value == 'unknown':
raise forms.ValidationError(_('Country field is required'))
if value == 'unknown':
return None
return value
class CountedWordsField(forms.CharField):
"""a field where a number of words is expected
to be in a certain range"""
def __init__(
self, min_words=0, max_words=9999, field_name=None,
*args, **kwargs
):
self.min_words = min_words
self.max_words = max_words
self.field_name = field_name
super(CountedWordsField, self).__init__(*args, **kwargs)
def clean(self, value):
#todo: this field must be adapted to work with Chinese, etc.
#for that we'll have to count characters instead of words
if value is None:
value = ''
value = value.strip()
word_count = len(value.split())
if word_count < self.min_words:
msg = ungettext_lazy(
'must be > %d word',
'must be > %d words',
self.min_words - 1
) % (self.min_words - 1)
#todo - space is not used in Chinese
raise forms.ValidationError(
string_concat(self.field_name, ' ', msg)
)
if word_count > self.max_words:
msg = ungettext_lazy(
'must be < %d word',
'must be < %d words',
self.max_words + 1
) % (self.max_words + 1)
raise forms.ValidationError(
string_concat(self.field_name, ' ', msg)
)
return value
class AskbotRecaptchaField(RecaptchaField):
"""A recaptcha field with preset keys from the livesettings"""
def __init__(self, *args, **kwargs):
kwargs.setdefault('private_key', askbot_settings.RECAPTCHA_SECRET)
kwargs.setdefault('public_key', askbot_settings.RECAPTCHA_KEY)
super(AskbotRecaptchaField, self).__init__(*args, **kwargs)
class LanguageField(forms.ChoiceField):
def __init__(self, *args, **kwargs):
kwargs['choices'] = django_settings.LANGUAGES
kwargs['label'] = _('Select language')
super(LanguageField, self).__init__(*args, **kwargs)
class LanguageForm(forms.Form):
language = LanguageField()
class LanguagePrefsForm(forms.Form):
languages = forms.MultipleChoiceField(
widget=forms.CheckboxSelectMultiple,
choices=django_settings.LANGUAGES,
required=False
)
primary_language = forms.ChoiceField(
choices=django_settings.LANGUAGES
)
class TranslateUrlForm(forms.Form):
language = LanguageField()
url = forms.CharField(max_length=2048)
class SuppressEmailField(forms.BooleanField):
def __init__(self):
super(SuppressEmailField, self).__init__()
self.required = False
self.label = _("minor edit (don't send alerts)")
class DomainNameField(forms.CharField):
"""Field for Internet Domain Names
todo: maybe there is a standard field for this?
"""
def clean(self, value):
#find a better regex, taking into account tlds
domain_re = re.compile(r'[a-zA-Z\d]+(\.[a-zA-Z\d]+)+')
if domain_re.match(value):
return value
else:
raise forms.ValidationError(
'%s is not a valid domain name' % value
)
class TitleField(forms.CharField):
"""Field receiving question title"""
def __init__(self, *args, **kwargs):
super(TitleField, self).__init__(*args, **kwargs)
self.required = kwargs.get('required', True)
self.widget = forms.TextInput(
attrs={'size': 70, 'autocomplete': 'off'}
)
self.max_length = 255
self.label = _('title')
self.help_text = askbot_settings.WORDS_PLEASE_ENTER_YOUR_QUESTION
self.initial = ''
def clean(self, value):
"""cleans the field for minimum and maximum length
also is supposed to work for unicode non-ascii characters"""
if value is None:
value = ''
if len(value) < askbot_settings.MIN_TITLE_LENGTH:
msg = ungettext_lazy(
'must have > %d character',
'must have > %d characters',
askbot_settings.MIN_TITLE_LENGTH
) % askbot_settings.MIN_TITLE_LENGTH
raise forms.ValidationError(msg)
encoded_value = value.encode('utf-8')
question_term = askbot_settings.WORDS_QUESTION_SINGULAR
if len(value) == len(encoded_value):
if len(value) > self.max_length:
raise forms.ValidationError(
_(
'The %(question)s is too long, maximum allowed size is '
'%(length)d characters'
) % {'question': question_term, 'length': self.max_length}
)
elif len(encoded_value) > self.max_length:
raise forms.ValidationError(
_(
'The %(question)s is too long, maximum allowed size is '
'%(length)d bytes'
) % {'question': question_term, 'length': self.max_length}
)
return value.strip() # TODO: test me
class EditorField(forms.CharField):
"""EditorField is subclassed by the
:class:`QuestionEditorField` and :class:`AnswerEditorField`
"""
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
if user is None:
raise ValueError('user parameter is required')
self.user = user
editor_attrs = kwargs.pop('editor_attrs', {})
widget_attrs = kwargs.pop('attrs', {})
widget_attrs.setdefault('id', 'editor')
super(EditorField, self).__init__(*args, **kwargs)
self.required = True
if askbot_settings.EDITOR_TYPE == 'markdown':
self.widget = forms.Textarea(attrs=widget_attrs)
elif askbot_settings.EDITOR_TYPE == 'tinymce':
self.widget = TinyMCE(attrs=widget_attrs, mce_attrs=editor_attrs)
self.label = _('content')
self.help_text = u''
self.initial = ''
self.min_length = 10
self.post_term_name = _('post')
def clean(self, value):
if value is None:
value = ''
if len(value) < self.min_length:
msg = ungettext_lazy(
'%(post)s content must be > %(count)d character',
'%(post)s content must be > %(count)d characters',
self.min_length
) % {'post': unicode(self.post_term_name), 'count': self.min_length}
raise forms.ValidationError(msg)
if self.user.is_anonymous():
#we postpone this validation if user is posting
#before logging in, up until publishing the post
return value
try:
self.user.assert_can_post_text(value)
except PermissionDenied, e:
raise forms.ValidationError(unicode(e))
return value
class QuestionEditorField(EditorField):
"""Editor field for the questions"""
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
super(QuestionEditorField, self).__init__(
user=user, *args, **kwargs
)
self.min_length = askbot_settings.MIN_QUESTION_BODY_LENGTH
self.post_term_name = askbot_settings.WORDS_QUESTION_SINGULAR
class AnswerEditorField(EditorField):
"""Editor field for answers"""
def __init__(self, *args, **kwargs):
super(AnswerEditorField, self).__init__(*args, **kwargs)
self.post_term_name = askbot_settings.WORDS_ANSWER_SINGULAR
self.min_length = askbot_settings.MIN_ANSWER_BODY_LENGTH
def clean_tag(tag_name, look_in_db=True):
"""a function that cleans a single tag name"""
tag_length = len(tag_name)
if tag_length > askbot_settings.MAX_TAG_LENGTH:
#singular form is odd in english, but required for pluralization
#in other languages
msg = ungettext_lazy(
#odd but added for completeness
'each tag must be shorter than %(max_chars)d character',
'each tag must be shorter than %(max_chars)d characters',
tag_length
) % {'max_chars': tag_length}
raise forms.ValidationError(msg)
#todo - this needs to come from settings
tagname_re = re.compile(const.TAG_REGEX, re.UNICODE)
if not tagname_re.search(tag_name):
if tag_name[0] in const.TAG_FORBIDDEN_FIRST_CHARS:
raise forms.ValidationError(
_(message_keys.TAG_WRONG_FIRST_CHAR_MESSAGE)
)
else:
raise forms.ValidationError(
_(message_keys.TAG_WRONG_CHARS_MESSAGE)
)
if askbot_settings.FORCE_LOWERCASE_TAGS:
#a simpler way to handle tags - just lowercase thew all
return tag_name.lower()
elif look_in_db == False:
return tag_name
else:
from askbot import models
matching_tags = models.Tag.objects.filter(
name__iexact=tag_name,
language_code=get_language()
)
if len(matching_tags) > 0:
return matching_tags[0].name
else:
return tag_name
class TagNamesField(forms.CharField):
"""field that receives AskBot tag names"""
def __init__(self, *args, **kwargs):
super(TagNamesField, self).__init__(*args, **kwargs)
self.required = kwargs.get('required',
askbot_settings.TAGS_ARE_REQUIRED)
self.widget = forms.TextInput(
attrs={'size': 50, 'autocomplete': 'off'}
)
self.max_length = 255
self.error_messages['max_length'] = _(
'We ran out of space for recording the tags. '
'Please shorten or delete some of them.'
)
self.label = kwargs.get('label') or _('tags')
self.help_text = kwargs.get('help_text') or ungettext_lazy(
'Tags are short keywords, with no spaces within. '
'Up to %(max_tags)d tag can be used.',
'Tags are short keywords, with no spaces within. '
'Up to %(max_tags)d tags can be used.',
askbot_settings.MAX_TAGS_PER_POST
) % {'max_tags': askbot_settings.MAX_TAGS_PER_POST}
self.initial = ''
def clean(self, value):
from askbot import models
value = super(TagNamesField, self).clean(value)
data = value.strip(const.TAG_STRIP_CHARS)
if len(data) < 1:
if askbot_settings.TAGS_ARE_REQUIRED:
raise forms.ValidationError(
_(message_keys.TAGS_ARE_REQUIRED_MESSAGE)
)
else:
#don't test for required characters when tags is ''
return ''
split_re = re.compile(const.TAG_SPLIT_REGEX)
tag_strings = split_re.split(data)
entered_tags = []
tag_count = len(tag_strings)
if tag_count > askbot_settings.MAX_TAGS_PER_POST:
max_tags = askbot_settings.MAX_TAGS_PER_POST
msg = ungettext_lazy(
'please use %(tag_count)d tag or less',
'please use %(tag_count)d tags or less',
tag_count) % {'tag_count': max_tags}
raise forms.ValidationError(msg)
if need_mandatory_tags():
if mandatory_tag_missing_in_list(tag_strings):
msg = _(
'At least one of the following tags is required : %(tags)s'
) % {'tags': get_text_list(models.tag.get_mandatory_tags())}
raise forms.ValidationError(msg)
cleaned_entered_tags = list()
for tag in tag_strings:
cleaned_tag = clean_tag(tag)
if cleaned_tag not in cleaned_entered_tags:
cleaned_entered_tags.append(clean_tag(tag))
result = u' '.join(cleaned_entered_tags)
if len(result) > 125:#magic number!, the same as max_length in db
raise forms.ValidationError(self.error_messages['max_length'])
return u' '.join(cleaned_entered_tags)
class WikiField(forms.BooleanField):
"""Rendered as checkbox turning post into
"community wiki"
"""
def __init__(self, *args, **kwargs):
super(WikiField, self).__init__(*args, **kwargs)
self.required = False
self.initial = False
self.label = _(
'community wiki (karma is not awarded & '
'many others can edit wiki post)'
)
def clean(self, value):
return value and askbot_settings.WIKI_ON
class PageField(forms.IntegerField):
def __init__(self, *args, **kwargs):
self.required = False
super(PageField, self).__init__(*args, **kwargs)
def clean(self, value):
try:
value = int(value)
return value if value > 0 else 1
except (TypeError, ValueError):
return 1
class SummaryField(forms.CharField):
def __init__(self, *args, **kwargs):
super(SummaryField, self).__init__(*args, **kwargs)
self.required = False
self.widget = forms.TextInput(
attrs={'size': 50, 'autocomplete': 'off'}
)
self.max_length = 300
self.label = _('update summary:')
self.help_text = _(
'enter a brief summary of your revision (e.g. '
'fixed spelling, grammar, improved style...), this '
'field is optional'
)
class EditorForm(forms.Form):
"""form with one field - `editor`
the field must be created dynamically, so it's added
in the __init__() function"""
def __init__(self, attrs=None, user=None, editor_attrs=None):
super(EditorForm, self).__init__()
editor_attrs = editor_attrs or {}
self.fields['editor'] = EditorField(
attrs=attrs,
editor_attrs=editor_attrs,
user=user
)
class DumpUploadForm(forms.Form):
"""This form handles importing
data into the forum. At the moment it only
supports stackexchange import.
"""
dump_file = forms.FileField()
class ShowQuestionForm(forms.Form):
"""Cleans data necessary to access answers and comments
by the respective comment or answer id - necessary
when comments would be normally wrapped and/or displayed
on the page other than the first page of answers to a question.
Same for the answers that are shown on the later pages.
"""
answer = forms.IntegerField(required=False)
comment = forms.IntegerField(required=False)
page = forms.IntegerField(required=False)
sort = forms.CharField(required=False)
def get_pruned_data(self):
nones = ('answer', 'comment', 'page')
for key in nones:
if key in self.cleaned_data:
if self.cleaned_data[key] is None:
del self.cleaned_data[key]
if 'sort' in self.cleaned_data:
if self.cleaned_data['sort'] == '':
del self.cleaned_data['sort']
return self.cleaned_data
def clean(self):
"""this form must always be valid
should use defaults if the data is incomplete
or invalid"""
if self._errors:
#since the form is always valid, clear the errors
logging.error(unicode(self._errors))
self._errors = {}
in_data = self.get_pruned_data()
out_data = dict()
default_answer_sort = askbot_settings.DEFAULT_ANSWER_SORT_METHOD
if ('answer' in in_data) ^ ('comment' in in_data):
out_data['show_page'] = None
out_data['answer_sort_method'] = default_answer_sort
out_data['show_comment'] = in_data.get('comment', None)
out_data['show_answer'] = in_data.get('answer', None)
else:
out_data['show_page'] = in_data.get('page', 1)
answer_sort_method = in_data.get('sort', default_answer_sort)
out_data['answer_sort_method'] = answer_sort_method
out_data['show_comment'] = None
out_data['show_answer'] = None
self.cleaned_data = out_data
return out_data
class ChangeUserReputationForm(forms.Form):
"""Form that allows moderators and site administrators
to adjust reputation of users.
this form internally verifies that user who claims to
be a moderator acually is
"""
user_reputation_delta = forms.IntegerField(
min_value=1,
max_value=32767,
label=_(
'Enter number of points to add or subtract'
)
)
comment = forms.CharField(label=_('Comment'), max_length=128)
def clean_comment(self):
if 'comment' in self.cleaned_data:
comment = self.cleaned_data['comment'].strip()
if comment == '':
del self.cleaned_data['comment']
raise forms.ValidationError('Please enter non-empty comment')
self.cleaned_data['comment'] = comment
return comment
MODERATOR_STATUS_CHOICES = (
('a', _('approved')),
('w', _('watched')),
('s', _('suspended')),
('b', _('blocked')),
)
ADMINISTRATOR_STATUS_CHOICES = (('d', _('administrator')),
('m', _('moderator')), ) \
+ MODERATOR_STATUS_CHOICES
class ChangeUserStatusForm(forms.Form):
"""form that allows moderators to change user's status
the type of options displayed depend on whether user
is a moderator or a site administrator as well as
what is the current status of the moderated user
for example moderators cannot moderate other moderators
and admins. Admins can take away admin status, but cannot
add it (that can be done through the Django Admin interface
this form is to be displayed in the user profile under
"moderation" tab
"""
user_status = forms.ChoiceField(label=_('Change status to'))
delete_content = forms.CharField(widget=forms.HiddenInput, initial='false')
def __init__(self, *arg, **kwarg):
moderator = kwarg.pop('moderator')
subject = kwarg.pop('subject')
super(ChangeUserStatusForm, self).__init__(*arg, **kwarg)
#select user_status_choices depending on status of the moderator
if moderator.is_authenticated():
if moderator.is_administrator():
user_status_choices = ADMINISTRATOR_STATUS_CHOICES
elif moderator.is_moderator():
user_status_choices = MODERATOR_STATUS_CHOICES
if subject.is_moderator() and subject != moderator:
raise ValueError('moderator cannot moderate another moderator')
else:
raise ValueError('moderator or admin expected from "moderator"')
#remove current status of the "subject" user from choices
user_status_choices = filter_choices(
remove_choices=[subject.status, ],
from_choices=user_status_choices
)
#add prompt option
user_status_choices = (('select', _('which one?')), ) \
+ user_status_choices
self.fields['user_status'].choices = user_status_choices
#set prompt option as default
self.fields['user_status'].default = 'select'
self.moderator = moderator
self.subject = subject
def clean_delete_content(self):
delete = self.cleaned_data.get('delete_content', False)
if delete == 'true':
delete = True
else:
delete = False
self.cleaned_data['delete_content'] = delete
return self.cleaned_data['delete_content']
def clean(self):
#if moderator is looking at own profile - do not
#let change status
if 'user_status' in self.cleaned_data:
user_status = self.cleaned_data['user_status']
#does not make sense to change own user status
#if necessary, this can be done from the Django admin interface
if self.moderator == self.subject:
del self.cleaned_data['user_status']
raise forms.ValidationError(_('Cannot change own status'))
#do not let moderators turn other users into moderators
if self.moderator.is_moderator() and user_status == 'moderator':
del self.cleanded_data['user_status']
raise forms.ValidationError(
_('Cannot turn other user to moderator')
)
#do not allow moderator to change status of other moderators
if self.moderator.is_moderator() and self.subject.is_moderator():
del self.cleaned_data['user_status']
raise forms.ValidationError(
_('Cannot change status of another moderator')
)
#do not allow moderator to change to admin
if self.moderator.is_moderator() and user_status == 'd':
raise forms.ValidationError(
_("Cannot change status to admin")
)
if user_status == 'select':
del self.cleaned_data['user_status']
msg = _(
'If you wish to change %(username)s\'s status, '
'please make a meaningful selection.'
) % {'username': self.subject.username}
raise forms.ValidationError(msg)
if user_status not in ('s', 'b'):#not blocked or suspended
if self.cleaned_data['delete_content'] == True:
self.cleaned_data['delete_content'] = False
return self.cleaned_data
class SendMessageForm(forms.Form):
subject_line = forms.CharField(
label=_('Subject line'),
max_length=64,
widget=forms.TextInput(attrs={'size': 64}, )
)
body_text = forms.CharField(
label=_('Message text'),
max_length=1600,
widget=forms.Textarea(attrs={'cols': 64})
)
class FeedbackForm(forms.Form):
name = forms.CharField(label=_('Your name (optional):'), required=False)
email = forms.EmailField(label=_('Email:'), required=False)
message = forms.CharField(
label=_('Your message:'),
widget=forms.Textarea(attrs={'cols': 60})
)
no_email = forms.BooleanField(
label=_("I don't want to give my email or receive a response:"),
required=False
)
next = NextUrlField()
def __init__(self, user=None, *args, **kwargs):
super(FeedbackForm, self).__init__(*args, **kwargs)
self.user = user
if should_use_recaptcha(user):
self.fields['recaptcha'] = AskbotRecaptchaField()
def clean_message(self):
message = self.cleaned_data.get('message', '').strip()
if not message:
raise forms.ValidationError(_('Message is required'))
return message
def clean(self):
super(FeedbackForm, self).clean()
if self.user and self.user.is_anonymous():
need_email = not bool(self.cleaned_data.get('no_email', False))
email = self.cleaned_data.get('email', '').strip()
if need_email and email == '':
msg = _('Either provide email address or mark "I dont want to give email below"')
self._errors['email'] = self.error_class([msg])
return self.cleaned_data
class FormWithHideableFields(object):
"""allows to swap a field widget to HiddenInput() and back"""
def hide_field(self, name):
"""replace widget with HiddenInput()
and save the original in the __hidden_fields dictionary
"""
if not hasattr(self, '__hidden_fields'):
self.__hidden_fields = dict()
if name in self.__hidden_fields:
return
self.__hidden_fields[name] = self.fields[name].widget
self.fields[name].widget = forms.HiddenInput()
def show_field(self, name):
"""restore the original widget on the field
if it was previously hidden
"""
if name in self.__hidden_fields:
self.fields[name] = self.__hidden_fields.pop(name)
class PostPrivatelyForm(forms.Form, FormWithHideableFields):
"""has a single field `post_privately` with
two related methods"""
post_privately = forms.BooleanField(
label = _('keep private within your groups'),
required = False
)
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
self._user = user
super(PostPrivatelyForm, self).__init__(*args, **kwargs)
if self.allows_post_privately() == False:
self.hide_field('post_privately')
def allows_post_privately(self):
user = self._user
return (
askbot_settings.GROUPS_ENABLED and \
user and user.is_authenticated() and \
user.can_make_group_private_posts()
)
def clean_post_privately(self):
if self.allows_post_privately() == False:
self.cleaned_data['post_privately'] = False
return self.cleaned_data['post_privately']
class DraftQuestionForm(forms.Form):
"""No real validation required for this form"""
title = forms.CharField(required=False)
text = forms.CharField(required=False)
tagnames = forms.CharField(required=False)
class DraftAnswerForm(forms.Form):
"""Only thread_id is required"""
thread_id = forms.IntegerField()
text = forms.CharField(required=False)
class PostAsSomeoneForm(forms.Form):
post_author_username = forms.CharField(
initial=_('User name:'),
help_text=_(
'Enter name to post on behalf of someone else. '
'Can create new accounts.'
),
required=False,
widget=forms.TextInput(attrs={'class': 'tipped-input blank'})
)
post_author_email = forms.CharField(
initial=_('Email address:'),
required=False,
widget=forms.TextInput(attrs={'class': 'tipped-input'})
)
def get_post_user(self, user):
"""returns user on whose behalf the post or a revision
is being made
"""
username = self.cleaned_data['post_author_username']
email= self.cleaned_data['post_author_email']
if user.is_administrator() and username and email:
post_user = user.get_or_create_fake_user(username, email)
else:
post_user = user
return post_user
def clean_post_author_username(self):
"""if value is the same as initial, it is reset to
empty string
todo: maybe better to have field where initial value is invalid,
then we would not have to have two almost identical clean functions?
"""
username = self.cleaned_data.get('post_author_username', '').strip()
initial_username = unicode(self.fields['post_author_username'].initial)
if username and username == initial_username:
self.cleaned_data['post_author_username'] = ''
return self.cleaned_data['post_author_username']
def clean_post_author_email(self):
"""if value is the same as initial, it is reset to
empty string"""
email = self.cleaned_data.get('post_author_email', '').strip()
initial_email = unicode(self.fields['post_author_email'].initial)
if email == initial_email:
email = ''
if email != '':
email = forms.EmailField().clean(email)
self.cleaned_data['post_author_email'] = email
return email
def clean(self):
"""requires email address if user name is given"""
username = self.cleaned_data.get('post_author_username', '')
email = self.cleaned_data.get('post_author_email', '')
if username == '' and email:
username_errors = self._errors.get(
'post_author_username',
ErrorList()
)
username_errors.append(_('User name is required with the email'))
self._errors['post_author_username'] = username_errors
raise forms.ValidationError('missing user name')
elif email == '' and username:
email_errors = self._errors.get('post_author_email', ErrorList())
email_errors.append(_('Email is required if user name is added'))
self._errors['post_author_email'] = email_errors
raise forms.ValidationError('missing email')
return self.cleaned_data
class AskForm(PostAsSomeoneForm, PostPrivatelyForm):
"""the form used to askbot questions
field ask_anonymously is shown to the user if the
if ALLOW_ASK_ANONYMOUSLY live setting is True
however, for simplicity, the value will always be present
in the cleaned data, and will evaluate to False if the
settings forbids anonymous asking
"""
tags = TagNamesField()
wiki = WikiField()
group_id = forms.IntegerField(required = False, widget = forms.HiddenInput)
openid = forms.CharField(
required=False, max_length=255,
widget=forms.TextInput(attrs={'size': 40, 'class': 'openid-input'})
)
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
super(AskForm, self).__init__(*args, **kwargs)
#it's important that this field is set up dynamically
self.fields['title'] = TitleField()
self.fields['text'] = QuestionEditorField(user=user)
self.fields['ask_anonymously'] = forms.BooleanField(
label=_('post anonymously'),
required=False
)
if user.is_anonymous() or not askbot_settings.ALLOW_ASK_ANONYMOUSLY:
self.hide_field('ask_anonymously')