-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathforms.py
executable file
·1030 lines (824 loc) · 36 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
__copyright__ = "Copyright 2017 Birkbeck, University of London"
__author__ = "Martin Paul Eve & Andy Byers"
__license__ = "AGPL v3"
__maintainer__ = "Birkbeck Centre for Technology and Publishing"
import re
import uuid
import json
from django import forms
from django.db import transaction
from django_select2.forms import Select2MultipleWidget
from django.db.models import Q
from django.forms.fields import Field
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.forms import UserCreationForm
from django.core.validators import validate_email, ValidationError
from tinymce.widgets import TinyMCE
from core import email, models, validators
from core.forms.fields import MultipleFileField, TagitField
from core.model_utils import JanewayBleachFormField, MiniHTMLFormField
from utils.logic import get_current_request
from journal import models as journal_models
from utils import render_template, setting_handler
from utils.forms import (
KeywordModelForm,
JanewayTranslationModelForm,
CaptchaForm,
HTMLDateInput,
)
from utils.logger import get_logger
from submission import models as submission_models
logger = get_logger(__name__)
class EditKey(forms.Form):
def __init__(self, *args, **kwargs):
self.key_type = kwargs.pop('key_type', None)
value = kwargs.pop('value', None)
super(EditKey, self).__init__(*args, **kwargs)
if self.key_type == 'rich-text':
self.fields['value'] = JanewayBleachFormField()
elif self.key_type == 'mini-html':
self.fields['value'] = MiniHTMLFormField()
elif self.key_type == 'text':
self.fields['value'].widget = forms.Textarea()
elif self.key_type == 'char':
self.fields['value'].widget = forms.TextInput()
elif self.key_type in {'number', 'integer'}:
# 'integer' is either a bug or used by a plugin
self.fields['value'].widget = forms.TextInput(attrs={'type': 'number'})
elif self.key_type == 'boolean':
self.fields['value'] = forms.BooleanField(widget=forms.CheckboxInput)
elif self.key_type == 'file' or self.key_type == 'journalthumb':
self.fields['value'].widget = forms.FileInput()
elif self.key_type == 'json':
self.fields['value'].widget = forms.Textarea()
else:
self.fields['value'].widget.attrs['size'] = '100%'
self.fields['value'].initial = value
self.fields['value'].required = False
self.fields['value'].label = ''
value = forms.CharField(label='')
def clean(self):
cleaned_data = self.cleaned_data
if self.key_type == 'json':
try:
json.loads(cleaned_data.get('value'))
except json.JSONDecodeError as e:
self.add_error(
'value',
f'JSON not valid: {e}',
)
return cleaned_data
class JournalContactForm(JanewayTranslationModelForm):
def __init__(self, *args, **kwargs):
next_sequence = kwargs.pop('next_sequence', None)
super(JournalContactForm, self).__init__(*args, **kwargs)
if next_sequence:
self.fields['sequence'].initial = next_sequence
class Meta:
model = models.Contacts
fields = ('name', 'email', 'role', 'sequence',)
exclude = ('content_type', 'object_id',)
class EditorialGroupForm(JanewayTranslationModelForm):
def __init__(self, *args, **kwargs):
next_sequence = kwargs.pop('next_sequence', None)
super(EditorialGroupForm, self).__init__(*args, **kwargs)
if next_sequence:
self.fields['sequence'].initial = next_sequence
class Meta:
model = models.EditorialGroup
fields = ('name', 'description', 'sequence', 'display_profile_images')
exclude = ('journal', 'press')
class PasswordResetForm(forms.Form):
password_1 = forms.CharField(widget=forms.PasswordInput, label=_('Password'))
password_2 = forms.CharField(widget=forms.PasswordInput, label=_('Repeat Password'))
def clean_password_2(self):
password_1 = self.cleaned_data.get("password_1")
password_2 = self.cleaned_data.get("password_2")
if password_1 and password_2 and password_1 != password_2:
raise forms.ValidationError(
'Your passwords do not match.',
code='password_mismatch',
)
return password_2
class GetResetTokenForm(forms.Form):
""" A form that validates password reset email addresses"""
email_address = forms.EmailField(
required=True,
label=_("Email"),
)
class RegistrationForm(forms.ModelForm, CaptchaForm):
""" A form that creates a user, with no privileges,
from the given username and password."""
password_1 = forms.CharField(widget=forms.PasswordInput, label=_('Password'))
password_2 = forms.CharField(widget=forms.PasswordInput, label=_('Repeat Password'))
register_as_reader = forms.BooleanField(
label='Register for Article Notifications',
help_text=_('Check this box if you would like to receive notifications of new articles published in this journal'),
required=False,
)
class Meta:
model = models.Account
fields = ('email', 'salutation', 'first_name', 'middle_name',
'last_name', 'department', 'institution', 'country', 'orcid',)
widgets = {'orcid': forms.HiddenInput() }
def __init__(self, *args, **kwargs):
self.journal = kwargs.pop('journal', None)
super(RegistrationForm, self).__init__(*args, **kwargs)
if not self.journal:
self.fields.pop('register_as_reader')
elif self.journal:
send_reader_notifications = setting_handler.get_setting(
'notifications',
'send_reader_notifications',
self.journal
).value
if not send_reader_notifications:
self.fields.pop('register_as_reader')
def clean_password_2(self):
password_1 = self.cleaned_data.get("password_1")
password_2 = self.cleaned_data.get("password_2")
if password_1 and password_2 and password_1 != password_2:
raise forms.ValidationError(
'Your passwords do not match.',
code='password_mismatch',
)
return password_2
def save(self, commit=True):
user = super(RegistrationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password_1"])
user.is_active = False
user.confirmation_code = uuid.uuid4()
user.email_sent = timezone.now()
if commit:
user.save()
if self.cleaned_data.get('register_as_reader') and self.journal:
user.add_account_role(
role_slug="reader",
journal=self.journal,
)
return user
class EditAccountForm(forms.ModelForm):
""" A form that creates a user, with no privileges, from the given username and password."""
interests = forms.CharField(required=False)
primary_study_topic = forms.ModelMultipleChoiceField(
queryset=models.Topics.objects.none(),
widget=Select2MultipleWidget,
required=False,
label=_('Primary Research Topics')
)
secondary_study_topic = forms.ModelMultipleChoiceField(
queryset=models.Topics.objects.none(),
widget=Select2MultipleWidget,
required=False,
label=_('Secondary Research Topics')
)
class Meta:
model = models.Account
exclude = ('email', 'username', 'activation_code', 'email_sent',
'date_confirmed', 'confirmation_code', 'is_active',
'is_staff', 'is_admin', 'date_joined', 'password',
'is_superuser', 'enable_digest')
widgets = {
'biography': TinyMCE(),
'signature': TinyMCE(),
'study_topic': Select2MultipleWidget,
}
def __init__(self, *args, **kwargs):
self.journal = kwargs.pop('journal', None)
super(EditAccountForm, self).__init__(*args, **kwargs)
if self.journal:
topics_queryset = models.Topics.objects.filter(
journal=self.journal,
).order_by('group__pretty_name', 'pretty_name')
self.fields['primary_study_topic'].queryset = topics_queryset
self.fields['secondary_study_topic'].queryset = topics_queryset
if 'instance' in kwargs:
account = kwargs['instance']
self.fields['primary_study_topic'].initial = account.topics('PR')
self.fields['secondary_study_topic'].initial = account.topics('SE')
study_topic_choices = [
(
group.pretty_name,
[
(topic.id, topic.pretty_name)
for topic in models.Topics.objects.filter(group=group).order_by('pretty_name')
]
)
for group in models.TopicGroup.objects.all()
]
self.fields['primary_study_topic'].choices = study_topic_choices
self.fields['secondary_study_topic'].choices = study_topic_choices
def save(self, commit=True):
user = super(EditAccountForm, self).save(commit=False)
user.clean()
posted_interests = self.cleaned_data['interests'].split(',')
for interest in posted_interests:
new_interest, c = models.Interest.objects.get_or_create(name=interest)
user.interest.add(new_interest)
for interest in user.interest.all():
if interest.name not in posted_interests:
user.interest.remove(interest)
user.save()
if commit:
user.save()
selected_primary_topic = set(self.cleaned_data['primary_study_topic'])
selected_secondary_topics = set(self.cleaned_data['secondary_study_topic'])
existing_topics = models.AccountTopic.objects.filter(account=user)
with transaction.atomic():
for topic in selected_secondary_topics:
models.AccountTopic.objects.update_or_create(
account=user,
topic=topic,
defaults={'topic_type': models.AccountTopic.SECONDARY}
)
for topic in selected_primary_topic:
models.AccountTopic.objects.update_or_create(
account=user,
topic=topic,
defaults={'topic_type': models.AccountTopic.PRIMARY}
)
for account_topic in existing_topics.filter(topic_type=models.AccountTopic.PRIMARY):
if account_topic.topic not in selected_primary_topic:
account_topic.delete()
for account_topic in existing_topics.filter(topic_type=models.AccountTopic.SECONDARY):
if account_topic.topic not in selected_secondary_topics:
account_topic.delete()
return user
class AdminUserForm(forms.ModelForm):
class Meta:
model = models.Account
fields = ('email', 'is_active', 'is_staff', 'is_admin', 'is_superuser')
def __init__(self, *args, **kwargs):
active = kwargs.pop('active', None)
request = kwargs.pop('request', None)
super(AdminUserForm, self).__init__(*args, **kwargs)
if not kwargs.get('instance', None):
self.fields['is_active'].initial = True
if active == 'add':
self.fields['password_1'] = forms.CharField(widget=forms.PasswordInput, label="Password")
self.fields['password_2'] = forms.CharField(widget=forms.PasswordInput, label="Repeat Password")
if request and not request.user.is_admin:
self.fields.pop('is_staff', None)
self.fields.pop('is_admin', None)
if request and not request.user.is_superuser:
self.fields.pop('is_superuser')
def clean_password_2(self):
password_1 = self.cleaned_data.get("password_1")
password_2 = self.cleaned_data.get("password_2")
if password_1 and password_2 and password_1 != password_2:
raise forms.ValidationError(
'Your passwords do not match.',
code='password_mismatch',
)
if password_2 and not len(password_2) >= 12:
raise forms.ValidationError(
'Your password is too short, it should be 12 characters or greater in length.',
code='password_to_short',
)
return password_2
def save(self, commit=True):
user = super(AdminUserForm, self).save(commit=False)
if self.cleaned_data.get('password_1'):
user.set_password(self.cleaned_data["password_1"])
user.save()
if commit:
user.save()
return user
class GeneratedPluginSettingForm(forms.Form):
def __init__(self, *args, **kwargs):
settings = kwargs.pop('settings', None)
super(GeneratedPluginSettingForm, self).__init__(*args, **kwargs)
for field in settings:
object = field['object']
if field['types'] == 'char':
self.fields[field['name']] = forms.CharField(widget=forms.TextInput(), required=False)
elif field['types'] == 'rich-text':
self.fields[field['name']] = JanewayBleachFormField(
required=False,
)
elif field['types'] == 'mini-html':
self.fields[field['name']] = MiniHTMLFormField(
required=False,
)
elif field['types'] in {'text', 'Text'}:
# Keeping Text because a plugin may use it
self.fields[field['name']] = forms.CharField(
widget=forms.Textarea,
required=False,
)
elif field['types'] == 'json':
self.fields[field['name']] = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,
choices=field['choices'],
required=False)
elif field['types'] == 'number':
self.fields[field['name']] = forms.CharField(widget=forms.TextInput(attrs={'type': 'number'}))
elif field['types'] == 'select':
self.fields[field['name']] = forms.CharField(widget=forms.Select(choices=field['choices']))
elif field['types'] == 'date':
self.fields[field['name']] = forms.CharField(
widget=forms.DateInput(attrs={'class': 'datepicker'}))
elif field['types'] == 'boolean':
self.fields[field['name']] = forms.BooleanField(
widget=forms.CheckboxInput(attrs={'is_checkbox': True}),
required=False)
self.fields[field['name']].initial = object.processed_value
self.fields[field['name']].help_text = object.setting.description
def save(self, journal, plugin, commit=True):
for setting_name, setting_value in self.cleaned_data.items():
setting_handler.save_plugin_setting(plugin, setting_name, setting_value, journal)
class GeneratedSettingForm(forms.Form):
def __init__(self, *args, **kwargs):
settings = kwargs.pop('settings', None)
super(GeneratedSettingForm, self).__init__(*args, **kwargs)
self.translatable_field_names = []
for field in settings:
object = field['object']
if object.setting.types == 'char':
self.fields[field['name']] = forms.CharField(widget=forms.TextInput(), required=False)
elif object.setting.types == 'rich-text':
self.fields[field['name']] = JanewayBleachFormField(
required=False,
)
elif object.setting.types == 'mini-html':
self.fields[field['name']] = MiniHTMLFormField(
required=False,
)
elif object.setting.types == 'text':
self.fields[field['name']] = forms.CharField(
widget=forms.Textarea,
required=False,
)
elif object.setting.types == 'json':
self.fields[field['name']] = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,
choices=field['choices'],
required=False)
elif object.setting.types == 'number':
self.fields[field['name']] = forms.CharField(widget=forms.TextInput(attrs={'type': 'number'}))
elif object.setting.types == 'select':
self.fields[field['name']] = forms.CharField(widget=forms.Select(choices=field['choices']))
elif object.setting.types == 'date':
self.fields[field['name']] = forms.CharField(
widget=forms.DateInput(attrs={'class': 'datepicker'}))
elif object.setting.types == 'boolean':
self.fields[field['name']] = forms.BooleanField(
widget=forms.CheckboxInput(attrs={'is_checkbox': True}),
required=False)
if object.setting.is_translatable:
self.translatable_field_names.append(object.setting.name)
self.fields[field['name']].label = object.setting.pretty_name
self.fields[field['name']].initial = object.processed_value
self.fields[field['name']].help_text = object.setting.description
def save(self, journal, group, commit=True):
for setting_name, setting_value in self.cleaned_data.items():
setting_handler.save_setting(group, setting_name, journal, setting_value)
class JournalAttributeForm(JanewayTranslationModelForm, KeywordModelForm):
class Meta:
model = journal_models.Journal
fields = (
'contact_info',
'is_remote',
'remote_view_url',
'remote_submit_url',
'hide_from_press',
)
class JournalImageForm(forms.ModelForm):
default_thumbnail = forms.FileField(required=False)
class Meta:
model = journal_models.Journal
fields = (
'header_image', 'default_cover_image',
'default_large_image', 'favicon', 'press_image_override',
'default_profile_image',
)
class JournalStylingForm(forms.ModelForm):
class Meta:
model = journal_models.Journal
fields = (
'full_width_navbar',
)
class JournalSubmissionForm(forms.ModelForm):
class Meta:
model = journal_models.Journal
fields = (
'enable_correspondence_authors',
)
class JournalArticleForm(forms.ModelForm):
class Meta:
model = journal_models.Journal
fields = (
'view_pdf_button',
'disable_metrics_display',
'disable_html_downloads',
)
class PressJournalAttrForm(KeywordModelForm, JanewayTranslationModelForm):
default_thumbnail = forms.FileField(required=False)
press_image_override = forms.FileField(required=False)
class Meta:
model = journal_models.Journal
fields = (
'contact_info', 'header_image', 'default_cover_image',
'default_large_image', 'favicon', 'is_remote', 'is_conference',
'remote_view_url', 'remote_submit_url', 'hide_from_press',
'disable_metrics_display',
)
class NotificationForm(forms.ModelForm):
class Meta:
model = journal_models.Notifications
exclude = ('journal',)
widgets = {
'active': forms.CheckboxInput(
attrs={
'is_checkbox': True,
}
),
}
class ArticleMetaImageForm(forms.ModelForm):
class Meta:
model = submission_models.Article
fields = ('meta_image',)
class SectionForm(JanewayTranslationModelForm):
class Meta:
model = submission_models.Section
fields = [
'name', 'plural', 'number_of_reviewers',
'is_filterable', 'sequence', 'section_editors',
'editors', 'jats_article_type', 'public_submissions', 'indexing',
'auto_assign_editors',
]
def __init__(self, *args, **kwargs):
request = kwargs.pop('request', None)
super(SectionForm, self).__init__(*args, **kwargs)
if request:
self.fields['section_editors'].queryset = request.journal.users_with_role(
'section-editor',
)
self.fields['section_editors'].required = False
self.fields['editors'].queryset = request.journal.users_with_role('editor')
self.fields['editors'].required = False
class TopicForm(forms.ModelForm):
class Meta:
model = models.Topics
fields = ['pretty_name', 'description', 'group']
labels = {
'pretty_name': 'Name',
'description': 'Description',
'group': 'Topic Group',
}
def __init__(self, *args, **kwargs):
request = kwargs.pop('request', None)
super(TopicForm, self).__init__(*args, **kwargs)
if request:
self.fields['group'].queryset = request.journal.topic_groups()
self.fields['group'].label_from_instance = lambda obj: "%s" % obj.pretty_name
class TopicGroupForm(forms.ModelForm):
class Meta:
model = models.TopicGroup
fields = ['pretty_name', 'description']
labels = {
'pretty_name': 'Name',
'description': 'Description',
}
def __init__(self, *args, **kwargs):
super(TopicGroupForm, self).__init__(*args, **kwargs)
def formatted_name(self, pretty_name: str):
return re.sub(r'\s+', '_', re.sub(r'[()]', '', pretty_name)).lower()
def save(self, commit=True, request=None):
topic_group = super(TopicGroupForm, self).save(commit=False)
if request:
topic_group_pretty_name = topic_group.pretty_name
topic_group.journal = request.journal
topic_group.name = self.formatted_name(topic_group_pretty_name)
if commit:
topic_group.save()
default_topic_name = f'{topic_group_pretty_name} (others)'
models.Topics.objects.create(
pretty_name=default_topic_name,
name=self.formatted_name(default_topic_name),
journal=request.journal,
group=topic_group,
description='another topics'
)
return topic_group
class QuickUserForm(forms.ModelForm):
class Meta:
model = models.Account
fields = ('email', 'salutation', 'first_name', 'last_name', 'institution',)
class LoginForm(CaptchaForm):
user_name = forms.CharField(max_length=255, label="Email")
user_pass = forms.CharField(max_length=255, label="Password", widget=forms.PasswordInput)
def __init__(self, *args, **kwargs):
bad_logins = kwargs.pop('bad_logins', 0)
super(LoginForm, self).__init__(*args, **kwargs)
if bad_logins:
logger.warning(
"[FAILED_LOGIN:%s][FAILURES: %s]"
"" % (self.fields["user_name"], bad_logins),
)
if bad_logins <= 3:
self.fields['captcha'] = forms.CharField(widget=forms.HiddenInput(), required=False)
class FileUploadForm(forms.Form):
file = forms.FileField()
def __init__(self, *args, extensions=None, mimetypes=None, **kwargs):
super().__init__(*args, **kwargs)
validator = validators.FileTypeValidator(
extensions=extensions,
mimetypes=mimetypes,
)
self.fields["file"].validators.append(validator)
class UserCreationFormExtended(UserCreationForm):
def __init__(self, *args, **kwargs):
super(UserCreationFormExtended, self).__init__(*args, **kwargs)
self.fields['email'] = forms.EmailField(
label=_("E-mail"),
max_length=75,
)
class XSLFileForm(forms.ModelForm):
class Meta:
model = models.XSLFile
exclude = ["date_uploaded", "journal", "original_filename"]
def save(self, commit=True):
instance = super().save(commit=False)
request = get_current_request()
if request:
instance.journal = request.journal
if commit:
instance.save()
return instance
class AccessRequestForm(forms.ModelForm):
class Meta:
model = models.AccessRequest
fields = ('text',)
labels = {
'text': 'Supporting Information',
}
def __init__(self, *args, **kwargs):
self.journal = kwargs.pop('journal', None)
self.repository = kwargs.pop('repository', None)
self.user = kwargs.pop('user')
self.role = kwargs.pop('role')
super(AccessRequestForm, self).__init__(*args, **kwargs)
def save(self, commit=True):
access_request = super().save(commit=False)
access_request.journal = self.journal
access_request.repository = self.repository
access_request.user = self.user
access_request.role = self.role
if commit:
access_request.save()
return access_request
class CBVFacetForm(forms.Form):
def __init__(self, *args, **kwargs):
# This form populates the facets that users can filter results on.
# The facets dynamically change based on the queryset of results,
# so users only see filter options that will have an effect on the
# current results.
self.id = 'facet_form'
self.queryset = kwargs.pop('queryset')
self.facets = kwargs.pop('facets')
self.fields = {}
super().__init__(*args, **kwargs)
for facet_key, facet in self.facets.items():
if facet['type'] == 'foreign_key':
# Note: This retrieval is written to work even for sqlite3.
# It might be rewritten differently if sqlite3 support isn't needed.
column = self.queryset.values_list(facet_key, flat=True)
values_list = list(filter(bool, column))
choice_queryset = facet['model'].objects.filter(pk__in=values_list)
choices = []
for each in choice_queryset:
label = getattr(each, facet["choice_label_field"])
count = self.queryset.filter(Q((facet_key, each.pk))).count()
label_with_count = f'{label} ({count})'
choices.append((each.pk, label_with_count))
choices = sorted(choices, key=lambda x: x[1])
self.fields[facet_key] = forms.ChoiceField(
widget=forms.widgets.CheckboxSelectMultiple,
choices=choices,
required=False,
)
elif facet['type'] == 'charfield_with_choices':
# Note: This retrieval is written to work even for sqlite3.
# It might be rewritten differently if sqlite3 support isn't needed.
column = []
values_list = []
lookup_parts = facet_key.split('.')
for obj in self.queryset:
for part in lookup_parts:
if obj:
try:
result = getattr(obj, part)
obj = result
except:
result = None
if result != None:
values_list.append(result)
elif result == None and 'default' in facet:
values_list.append(facet['default'])
unique_values = set(values_list)
choices = []
model_choice_dict = dict(facet['model_choices'])
for value in unique_values:
label = model_choice_dict.get(value, value)
count = values_list.count(value)
label_with_count = f'{label} ({count})'
choices.append((value, label_with_count))
self.fields[facet_key] = forms.ChoiceField(
widget=forms.widgets.CheckboxSelectMultiple,
choices=choices,
required=False,
)
elif facet['type'] == 'date_time':
self.fields[facet_key] = forms.DateTimeField(
required=False,
widget=forms.DateTimeInput(
attrs={'type': 'datetime-local'}
),
)
elif facet['type'] == 'date':
self.fields[facet_key] = forms.DateField(
required=False,
widget=forms.DateInput(
attrs={'type': 'date'}
),
)
elif facet['type'] == 'integer':
self.fields[facet_key] = forms.IntegerField(
required=False,
)
elif facet['type'] == 'search':
self.fields[facet_key] = forms.CharField(
required=False,
widget=forms.TextInput(
attrs={'type': 'search'}
),
)
elif facet['type'] == 'boolean':
self.fields[facet_key] = forms.TypedChoiceField(
widget=forms.widgets.RadioSelect,
choices=[
('', facet.get('all_label', 'All')),
(1, facet.get('true_label', 'Yes')),
(0, facet.get('false_label', 'No')),
],
required=False,
coerce=int,
)
self.fields[facet_key].label = facet['field_label']
def order_by(self, queryset, facet, fks):
order_by = facet.get('order_by')
if order_by != 'facet_count' and order_by in facet['model']._meta.get_fields():
queryset = queryset.order_by(order_by)
elif order_by == 'facet_count':
sorted_fk_tuples = sorted(
[(fk, fks.count(fk)) for fk in fks],
key=lambda x:x[1],
reverse=True,
)
sorted_fks = [tup[0] for tup in sorted_fk_tuples]
queryset = sorted(
queryset,
key=lambda x: sorted_fks.index(x.pk)
)
return queryset
class ConfirmableForm(forms.Form):
"""
Adds a modal at form submission asking
the user a question and showing them
potential problems with how they
completed the form. Different from
validation because potential errors
are more nuanced than invalid data.
The modal always appears on submission,
even if there are no potential errors.
For a version where the modal only appears
if there are errrors, see ConfirmableIfErrorsForm.
"""
CONFIRMABLE_BUTTON_NAME = 'confirmable'
CONFIRMED_BUTTON_NAME = 'confirmed'
QUESTION = _('Are you sure?')
def __init__(self, *args, **kwargs):
self.modal = None
super().__init__(*args, **kwargs)
def is_valid(self, *args, **kwargs):
parent_return = super().is_valid(*args, **kwargs)
if self.CONFIRMABLE_BUTTON_NAME in self.data:
self.create_modal()
return parent_return
def create_modal(self):
self.modal = {
'id': 'confirm_modal',
'confirmed_button_name': self.CONFIRMED_BUTTON_NAME,
'question': self.QUESTION,
'potential_errors': self.check_for_potential_errors(),
}
def check_for_potential_errors(self):
return []
def check_for_inactive_account(self, account):
if not isinstance(account, models.Account):
try:
account = models.Account.objects.get(id=account)
except models.Account.DoesNotExist:
return 'Could not check account status'
if not account.is_active:
return _('The account belonging to %(email)s has not yet been activated, ' \
'so the recipient of this assignment may not be able ' \
'to log in and view it.') % {'email': account.email}
def is_confirmed(self):
return self.CONFIRMED_BUTTON_NAME in self.data
class ConfirmableIfErrorsForm(ConfirmableForm):
"""
A variant of ConfirmableForm
that only shows the modal if
there are potential errors.
Otherwise it submits the form.
"""
def create_modal(self):
if self.check_for_potential_errors():
super().create_modal()
def is_confirmed(self):
if self.check_for_potential_errors():
return super().is_confirmed()
else:
return True
class EmailForm(forms.Form):
cc = TagitField(
required=False,
max_length=10000,
)
bcc = TagitField(
required=False,
max_length=10000,
)
subject = forms.CharField(max_length=1000)
body = forms.CharField(widget=TinyMCE)
attachments = MultipleFileField(required=False)
def clean_cc(self):
cc = self.cleaned_data['cc']
return self.email_sequence_cleaner("cc", cc)
def clean_bcc(self):
cc = self.cleaned_data['bcc']
return self.email_sequence_cleaner("bcc", cc)
def email_sequence_cleaner(self, field, email_seq):
if not email_seq or email_seq == '':
return tuple()
for address in email_seq:
try:
validate_email(address)
except ValidationError:
self.add_error(field, 'Invalid email address ({}).'.format(address))
return email_seq
def as_dataclass(self):
return email.EmailData(**self.cleaned_data)
class FullEmailForm(EmailForm):
""" An email form that includes the To field
"""
to = TagitField(
required=True,
max_length=10000,
)
field_order = ['to', 'cc', 'bcc', 'subject', 'body', 'attachments']
def clean_to(self):
to = self.cleaned_data['to']
return self.email_sequence_cleaner("to", to)
class SettingEmailForm(EmailForm):
""" An Email form that populates initial data using Janeway email settings
During initialization, the email and subject settings are retrieved,
matching the given setting_name
:param setting_name: The name of the setting (Group must be email)
:param email_context: A dict of the context required to populate the email
:param request: The instance of this HttpRequest
:param journal: (Optional) an instance of journal.models.Journal
"""
def __init__(self, *args, **kwargs):
setting_name = kwargs.pop("setting_name")
email_context = kwargs.pop("email_context", {})
subject_setting_name = "subject_" + setting_name
request = kwargs.pop("request")
journal = kwargs.pop("journal", None) or request.journal
initial_subject = setting_handler.get_email_subject_setting(
setting_name=subject_setting_name,
journal=journal,
)