forked from ietf-tools/datatracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathforms.py
More file actions
1166 lines (988 loc) · 48.8 KB
/
forms.py
File metadata and controls
1166 lines (988 loc) · 48.8 KB
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 The IETF Trust 2016-2025, All Rights Reserved
# -*- coding: utf-8 -*-
import io
import os
import datetime
import json
import re
from pathlib import Path
from django import forms
from django.conf import settings
from django.core import validators
from django.core.exceptions import ValidationError
from django.forms import BaseInlineFormSet
from django.template.defaultfilters import pluralize
from django.utils.functional import cached_property
from django.utils.safestring import mark_safe
import debug # pyflakes:ignore
from ietf.doc.models import Document, State, NewRevisionDocEvent
from ietf.group.models import Group
from ietf.group.utils import groups_managed_by
from ietf.meeting.models import (Session, Meeting, Schedule, COUNTRIES, TIMEZONES, TimeSlot, Room,
Constraint, ResourceAssociation)
from ietf.meeting.helpers import get_next_interim_number, make_materials_directories
from ietf.meeting.helpers import is_interim_meeting_approved, get_next_agenda_name
from ietf.message.models import Message
from ietf.name.models import TimeSlotTypeName, SessionPurposeName, TimerangeName, ConstraintName
from ietf.person.fields import SearchablePersonsField
from ietf.person.models import Person
from ietf.utils import log
from ietf.utils.fields import (
DatepickerDateField,
DatepickerSplitDateTimeWidget,
DurationField,
ModelMultipleChoiceField,
MultiEmailField,
)
from ietf.utils.html import clean_text_field
from ietf.utils.validators import ( validate_file_size, validate_mime_type,
validate_file_extension, validate_no_html_frame)
NUM_SESSION_CHOICES = (('', '--Please select'), ('1', '1'), ('2', '2'))
SESSION_TIME_RELATION_CHOICES = (('', 'No preference'),) + Constraint.TIME_RELATION_CHOICES
JOINT_FOR_SESSION_CHOICES = (('1', 'First session'), ('2', 'Second session'), ('3', 'Third session'), )
# -------------------------------------------------
# Helpers
# -------------------------------------------------
class GroupModelChoiceField(forms.ModelChoiceField):
'''
Custom ModelChoiceField, changes the label to a more readable format
'''
def label_from_instance(self, obj):
return obj.acronym
class CustomDurationField(DurationField):
"""Custom DurationField to display as HH:MM (no seconds)"""
widget = forms.TextInput(dict(placeholder='HH:MM'))
def prepare_value(self, value):
if isinstance(value, datetime.timedelta):
return duration_string(value)
return value
def duration_string(duration):
'''Custom duration_string to return HH:MM (no seconds)'''
days = duration.days
seconds = duration.seconds
minutes = seconds // 60
hours = minutes // 60
minutes = minutes % 60
string = '{:02d}:{:02d}'.format(hours, minutes)
if days:
string = '{} '.format(days) + string
return string
def allowed_conflicting_groups():
return Group.objects.filter(
type__in=['wg', 'ag', 'rg', 'rag', 'program', 'edwg'],
state__in=['bof', 'proposed', 'active'])
def check_conflict(groups, source_group):
'''
Takes a string which is a list of group acronyms. Checks that they are all active groups
'''
# convert to python list (allow space or comma separated lists)
items = groups.replace(',', ' ').split()
active_groups = allowed_conflicting_groups()
for group in items:
if group == source_group.acronym:
raise forms.ValidationError("Cannot declare a conflict with the same group: %s" % group)
if not active_groups.filter(acronym=group):
raise forms.ValidationError("Invalid or inactive group acronym: %s" % group)
# -------------------------------------------------
# Forms
# -------------------------------------------------
class InterimSessionInlineFormSet(BaseInlineFormSet):
def __init__(self, *args, **kwargs):
super(InterimSessionInlineFormSet, self).__init__(*args, **kwargs)
if 'data' in kwargs:
self.meeting_type = kwargs['data']['meeting_type']
def clean(self):
'''Custom clean method to verify dates are consecutive for multi-day meetings'''
super(InterimSessionInlineFormSet, self).clean()
if self.meeting_type == 'multi-day':
dates = []
for form in self.forms:
date = form.cleaned_data.get('date')
if date:
dates.append(date)
if len(dates) < 2:
return
dates.sort()
last_date = dates[0]
for date in dates[1:]:
if date - last_date != datetime.timedelta(days=1):
raise forms.ValidationError('For Multi-Day meetings, days must be consecutive')
last_date = date
self.days = len(dates)
return # formset doesn't have cleaned_data
class InterimMeetingModelForm(forms.ModelForm):
group = GroupModelChoiceField(
queryset=Group.objects.with_meetings().filter(
state__in=('active', 'proposed', 'bof')
).order_by('acronym'),
required=False,
empty_label="Click to select",
)
group.widget.attrs['data-max-entries'] = 1
group.widget.attrs['data-minimum-input-length'] = 0
in_person = forms.BooleanField(required=False)
meeting_type = forms.ChoiceField(
choices=(
("single", "Single"),
("multi-day", "Multi-Day"),
('series', 'Series')
),
required=False,
initial='single',
widget=forms.RadioSelect,
help_text='''
Use <b>Multi-Day</b> for a single meeting that spans more than one contiguous
workday. Do not use Multi-Day for a series of separate meetings (such as
periodic interim calls). Use Series instead.
Use <b>Series</b> for a series of separate meetings, such as periodic interim calls.
Use Multi-Day for a single meeting that spans more than one contiguous
workday.''',
)
approved = forms.BooleanField(required=False)
city = forms.CharField(max_length=255, required=False)
city.widget.attrs['placeholder'] = "City"
country = forms.ChoiceField(choices=COUNTRIES, required=False)
country.widget.attrs['class'] = "select2-field"
country.widget.attrs['data-max-entries'] = 1
country.widget.attrs['data-placeholder'] = "Country"
country.widget.attrs['data-minimum-input-length'] = 0
time_zone = forms.ChoiceField(choices=TIMEZONES)
time_zone.widget.attrs['class'] = "select2-field"
time_zone.widget.attrs['data-max-entries'] = 1
time_zone.widget.attrs['data-minimum-input-length'] = 0
class Meta:
model = Meeting
fields = ('group', 'in_person', 'meeting_type', 'approved', 'city', 'country', 'time_zone')
def __init__(self, request, *args, **kwargs):
super(InterimMeetingModelForm, self).__init__(*args, **kwargs)
self.user = request.user
self.person = self.user.person
self.is_edit = bool(self.instance.pk)
self.fields['group'].widget.attrs['class'] = "select2-field"
self.fields['time_zone'].initial = 'UTC'
self.fields['approved'].initial = True
self.set_group_options()
if self.is_edit:
self.fields['group'].initial = self.instance.session_set.first().group
self.fields['group'].widget.attrs['disabled'] = True
if self.instance.city or self.instance.country:
self.fields['in_person'].initial = True
if is_interim_meeting_approved(self.instance):
self.fields['approved'].initial = True
else:
self.fields['approved'].initial = False
self.fields['approved'].widget.attrs['disabled'] = True
def clean(self):
super(InterimMeetingModelForm, self).clean()
cleaned_data = self.cleaned_data
if not cleaned_data.get('group'):
raise forms.ValidationError("You must select a group")
return self.cleaned_data
def is_virtual(self):
if not self.is_bound or self.data.get('in_person'):
return False
else:
return True
def set_group_options(self):
"""Set group options based on user accessing the form"""
queryset = groups_managed_by(
self.user,
Group.objects.with_meetings(),
).filter(
state_id__in=['active', 'proposed', 'bof']
).order_by('acronym')
self.fields['group'].queryset = queryset
# if there's only one possibility make it the default
if len(queryset) == 1:
self.fields['group'].initial = queryset[0]
def save(self, *args, **kwargs):
'''Save must handle fields not included in the form: date,number,type_id'''
date = kwargs.pop('date')
group = self.cleaned_data.get('group')
meeting = super(InterimMeetingModelForm, self).save(commit=False)
if not meeting.type_id:
meeting.type_id = 'interim'
if not meeting.number:
meeting.number = get_next_interim_number(group.acronym, date)
meeting.date = date
meeting.days = 1
if kwargs.get('commit', True):
# create schedule with meeting
meeting.save() # pre-save so we have meeting.pk for schedule
if not meeting.schedule:
meeting.schedule = Schedule.objects.create(
meeting=meeting,
owner=Person.objects.get(name='(System)'))
meeting.save() # save with schedule
# create directories
make_materials_directories(meeting)
return meeting
class InterimSessionModelForm(forms.ModelForm):
date = DatepickerDateField(date_format="yyyy-mm-dd", picker_settings={"autoclose": "1"}, label='Date', required=False)
time = forms.TimeField(widget=forms.TimeInput(format='%H:%M'), required=True, help_text="Start time in meeting time zone")
time.widget.attrs['placeholder'] = "HH:MM"
requested_duration = CustomDurationField(required=True)
end_time = forms.TimeField(required=False, help_text="End time in meeting time zone")
end_time.widget.attrs['placeholder'] = "HH:MM"
remote_participation = forms.ChoiceField(choices=(), required=False)
remote_instructions = forms.CharField(
max_length=1024,
required=False,
help_text='''
For virtual interims, a conference link <b>should be provided in the original request</b> in all but the most unusual circumstances.
Otherwise, "Remote participation is not supported" or "Remote participation information will be obtained at the time of approval" are acceptable values.
See <a href="https://www.ietf.org/forms/wg-webex-account-request/">here</a> for more on remote participation support.
''',
)
agenda = forms.CharField(required=False, widget=forms.Textarea, strip=False)
agenda.widget.attrs['placeholder'] = "Paste agenda here"
agenda_note = forms.CharField(max_length=255, required=False, label=" Additional information")
class Meta:
model = Session
fields = ('date', 'time', 'requested_duration', 'end_time',
'remote_instructions', 'agenda', 'agenda_note')
def __init__(self, *args, **kwargs):
if 'user' in kwargs:
self.user = kwargs.pop('user')
if 'group' in kwargs:
self.group = kwargs.pop('group')
if 'requires_approval' in kwargs:
self.requires_approval = kwargs.pop('requires_approval')
super(InterimSessionModelForm, self).__init__(*args, **kwargs)
self.is_edit = bool(self.instance.pk)
# setup fields that aren't intrinsic to the Session object
if self.is_edit:
self.initial['date'] = self.instance.official_timeslotassignment().timeslot.local_start_time().date()
self.initial['time'] = self.instance.official_timeslotassignment().timeslot.local_start_time().time()
if self.instance.agenda():
doc = self.instance.agenda()
content = doc.text_or_error()
self.initial['agenda'] = content
# set up remote participation choices
choices = []
if hasattr(settings, 'MEETECHO_API_CONFIG'):
choices.append(('meetecho', 'Automatically create Meetecho conference'))
choices.append(('manual', 'Manually specify remote instructions...'))
self.fields['remote_participation'].choices = choices
# put remote_participation ahead of remote_instructions
field_order = [field for field in self.fields if field != 'remote_participation']
field_order.insert(field_order.index('remote_instructions'), 'remote_participation')
self.order_fields(field_order)
def clean_date(self):
'''Date field validator. We can't use required on the input because
it is a datepicker widget'''
date = self.cleaned_data.get('date')
if not date:
raise forms.ValidationError('Required field')
return date
def clean_requested_duration(self):
min_minutes = settings.INTERIM_SESSION_MINIMUM_MINUTES
max_minutes = settings.INTERIM_SESSION_MAXIMUM_MINUTES
duration = self.cleaned_data.get('requested_duration')
if not duration or duration < datetime.timedelta(minutes=min_minutes) or duration > datetime.timedelta(minutes=max_minutes):
raise forms.ValidationError('Provide a duration, %s-%smin.' % (min_minutes, max_minutes))
return duration
def clean(self):
if self.cleaned_data.get('remote_participation', None) == 'meetecho':
self.cleaned_data['remote_instructions'] = '' # blank this out if we're creating a Meetecho conference
elif not self.cleaned_data['remote_instructions']:
self.add_error('remote_instructions', 'This field is required')
return self.cleaned_data
# Override to ignore the non-model 'remote_participation' field when computing has_changed()
@cached_property
def changed_data(self):
data = super().changed_data
if 'remote_participation' in data:
data.remove('remote_participation')
return data
def save(self, *args, **kwargs):
"""NOTE: as the baseform of an inlineformset self.save(commit=True)
never gets called"""
session = super(InterimSessionModelForm, self).save(commit=False)
session.group = self.group
session.type_id = 'regular'
session.purpose_id = 'regular'
if kwargs.get('commit', True) is True:
super(InterimSessionModelForm, self).save(commit=True)
return session
def save_agenda(self):
if self.instance.agenda():
doc = self.instance.agenda()
doc.rev = str(int(doc.rev) + 1).zfill(2)
doc.uploaded_filename = doc.filename_with_rev()
e = NewRevisionDocEvent.objects.create(
type='new_revision',
by=self.user.person,
doc=doc,
rev=doc.rev,
desc='New revision available')
doc.save_with_history([e])
else:
filename = get_next_agenda_name(meeting=self.instance.meeting)
doc = Document.objects.create(
type_id='agenda',
group=self.group,
name=filename,
rev='00',
# FIXME: if these are always computed, they shouldn't be in uploaded_filename - just compute them when needed
# FIXME: What about agendas in html or markdown format?
uploaded_filename='{}-00.txt'.format(filename))
doc.set_state(State.objects.get(type__slug=doc.type.slug, slug='active'))
self.instance.presentations.create(document=doc, rev=doc.rev)
NewRevisionDocEvent.objects.create(
type='new_revision',
by=self.user.person,
doc=doc,
rev=doc.rev,
desc='New revision available')
# write file
path = os.path.join(self.instance.meeting.get_materials_path(), 'agenda', doc.filename_with_rev())
directory = os.path.dirname(path)
if not os.path.exists(directory):
os.makedirs(directory)
with io.open(path, "w", encoding='utf-8') as file:
file.write(self.cleaned_data['agenda'])
doc.store_str(doc.uploaded_filename, self.cleaned_data['agenda'])
class InterimAnnounceForm(forms.ModelForm):
class Meta:
model = Message
fields = ('to', 'cc', 'frm', 'subject', 'body')
def __init__(self, *args, **kwargs):
super(InterimAnnounceForm, self).__init__(*args, **kwargs)
self.fields['frm'].label='From'
self.fields['frm'].widget.attrs['readonly'] = True
self.fields['to'].widget.attrs['readonly'] = True
def save(self, *args, **kwargs):
user = kwargs.pop('user')
message = super(InterimAnnounceForm, self).save(commit=False)
message.by = user.person
message.save()
return message
class InterimCancelForm(forms.Form):
group = forms.CharField(max_length=255, required=False)
date = forms.DateField(required=False)
# max_length must match Session.agenda_note
comments = forms.CharField(max_length=512, required=False, widget=forms.Textarea(attrs={'placeholder': 'enter optional comments here'}), strip=False)
def __init__(self, *args, **kwargs):
super(InterimCancelForm, self).__init__(*args, **kwargs)
self.fields['group'].widget.attrs['disabled'] = True
self.fields['date'].widget.attrs['disabled'] = True
class FileUploadForm(forms.Form):
"""Base class for FileUploadForms
Abstract base class - subclasses must fill in the doc_type value with
the type of document they handle.
"""
file = forms.FileField(label='File to upload')
doc_type = '' # subclasses must set this
def __init__(self, *args, **kwargs):
assert self.doc_type in settings.MEETING_VALID_UPLOAD_EXTENSIONS
self.extensions = settings.MEETING_VALID_UPLOAD_EXTENSIONS[self.doc_type]
self.mime_types = settings.MEETING_VALID_UPLOAD_MIME_TYPES[self.doc_type]
super(FileUploadForm, self).__init__(*args, **kwargs)
label = '%s file to upload. ' % (self.doc_type.capitalize(), )
if self.doc_type == "slides":
label += 'Did you remember to put in slide numbers? '
if self.mime_types:
label += 'Note that you can only upload files with these formats: %s.' % (', '.join(self.mime_types, ))
self.fields['file'].label=label
def clean_file(self):
file = self.cleaned_data['file']
validate_file_size(file)
ext = validate_file_extension(file, self.extensions)
# override the Content-Type if needed
if file.content_type in 'application/octet-stream':
content_type_map = settings.MEETING_APPLICATION_OCTET_STREAM_OVERRIDES
filename = Path(file.name)
if filename.suffix in content_type_map:
file.content_type = content_type_map[filename.suffix]
self.cleaned_data['file'] = file
mime_type, encoding = validate_mime_type(file, self.mime_types)
if not hasattr(self, 'file_encoding'):
self.file_encoding = {}
self.file_encoding[file.name] = encoding or None
if self.mime_types:
if not file.content_type in settings.MEETING_VALID_UPLOAD_MIME_FOR_OBSERVED_MIME[mime_type]:
raise ValidationError('Upload Content-Type (%s) is different from the observed mime-type (%s)' % (file.content_type, mime_type))
# We just validated that file.content_type is safe to accept despite being identified
# as a different MIME type by the validator. Check extension based on file.content_type
# because that better reflects the intention of the upload client.
if file.content_type in settings.MEETING_VALID_MIME_TYPE_EXTENSIONS:
if not ext in settings.MEETING_VALID_MIME_TYPE_EXTENSIONS[file.content_type]:
raise ValidationError('Upload Content-Type (%s) does not match the extension (%s)' % (file.content_type, ext))
if (file.content_type in ['text/html', ]
or ext in settings.MEETING_VALID_MIME_TYPE_EXTENSIONS.get('text/html', [])):
# We'll do html sanitization later, but for frames, we fail here,
# as the sanitized version will most likely be useless.
validate_no_html_frame(file)
return file
class UploadBlueSheetForm(FileUploadForm):
doc_type = 'bluesheets'
class ApplyToAllFileUploadForm(FileUploadForm):
"""FileUploadField that adds an apply_to_all checkbox
Checkbox can be disabled by passing show_apply_to_all_checkbox=False to the constructor.
This entirely removes the field from the form.
"""
# Note: subclasses must set doc_type for FileUploadForm
apply_to_all = forms.BooleanField(label='Apply to all group sessions at this meeting',initial=True,required=False)
def __init__(self, show_apply_to_all_checkbox, *args, **kwargs):
super().__init__(*args, **kwargs)
if not show_apply_to_all_checkbox:
self.fields.pop('apply_to_all')
else:
self.order_fields(
sorted(
self.fields.keys(),
key=lambda f: 'zzzzzz' if f == 'apply_to_all' else f
)
)
class UploadMinutesForm(ApplyToAllFileUploadForm):
doc_type = 'minutes'
class UploadNarrativeMinutesForm(ApplyToAllFileUploadForm):
doc_type = 'narrativeminutes'
class UploadAgendaForm(ApplyToAllFileUploadForm):
doc_type = 'agenda'
class UploadSlidesForm(ApplyToAllFileUploadForm):
doc_type = 'slides'
title = forms.CharField(max_length=255)
approved = forms.BooleanField(label='Auto-approve', initial=True, required=False)
def __init__(self, session, show_apply_to_all_checkbox, can_manage, *args, **kwargs):
super().__init__(show_apply_to_all_checkbox, *args, **kwargs)
if not can_manage:
self.fields.pop('approved')
self.session = session
def clean_title(self):
title = self.cleaned_data['title']
# The current tables only handles Unicode BMP:
if ord(max(title)) > 0xffff:
raise forms.ValidationError("The title contains characters outside the Unicode BMP, which is not currently supported")
if self.session.meeting.type_id=='interim':
if re.search(r'-\d{2}$', title):
raise forms.ValidationError("Interim slides currently may not have a title that ends with something that looks like a revision number (-nn)")
return title
class ImportMinutesForm(forms.Form):
markdown_text = forms.CharField(strip=False, widget=forms.HiddenInput)
class RequestMinutesForm(forms.Form):
to = MultiEmailField()
cc = MultiEmailField(required=False)
subject = forms.CharField()
body = forms.CharField(widget=forms.Textarea,strip=False)
class SwapDaysForm(forms.Form):
source_day = forms.DateField(required=True)
target_day = forms.DateField(required=True)
class CsvModelPkInput(forms.TextInput):
"""Text input that expects a CSV list of PKs of a model instances"""
def format_value(self, value):
"""Convert value to contents of input text widget
Value is a list of pks, or None
"""
return '' if value is None else ','.join(str(v) for v in value)
def value_from_datadict(self, data, files, name):
"""Convert data back to list of PKs"""
value = super(CsvModelPkInput, self).value_from_datadict(data, files, name)
return value.split(',')
class SwapTimeslotsForm(forms.Form):
"""Timeslot swap form
Interface uses timeslot instances rather than time/duration to simplify handling in
the JavaScript. This might make more sense with a DateTimeField and DurationField for
origin/target. Instead, grabs time and duration from a TimeSlot.
This is not likely to be practical as a rendered form. Current use is to validate
data from an ad hoc form. In an ideal world, this would be refactored to use a complex
custom widget, but unless it proves to be reused that would be a poor investment of time.
"""
origin_timeslot = forms.ModelChoiceField(
required=True,
queryset=TimeSlot.objects.none(), # default to none, fill in when we have a meeting
widget=forms.TextInput,
)
target_timeslot = forms.ModelChoiceField(
required=True,
queryset=TimeSlot.objects.none(), # default to none, fill in when we have a meeting
widget=forms.TextInput,
)
rooms = ModelMultipleChoiceField(
required=True,
queryset=Room.objects.none(), # default to none, fill in when we have a meeting
widget=CsvModelPkInput,
)
def __init__(self, meeting, *args, **kwargs):
super(SwapTimeslotsForm, self).__init__(*args, **kwargs)
self.meeting = meeting
self.fields['origin_timeslot'].queryset = meeting.timeslot_set.all()
self.fields['target_timeslot'].queryset = meeting.timeslot_set.all()
self.fields['rooms'].queryset = meeting.room_set.all()
class TimeSlotDurationField(CustomDurationField):
"""Duration field for TimeSlot edit / create forms"""
default_validators=[
validators.MinValueValidator(datetime.timedelta(seconds=0)),
validators.MaxValueValidator(datetime.timedelta(hours=12)),
]
def __init__(self, **kwargs):
kwargs.setdefault('help_text', 'Duration of timeslot in hours and minutes')
super().__init__(**kwargs)
class TimeSlotEditForm(forms.ModelForm):
class Meta:
model = TimeSlot
fields = ('name', 'type', 'time', 'duration', 'show_location', 'location')
field_classes = dict(
time=forms.SplitDateTimeField,
duration=TimeSlotDurationField
)
widgets = dict(
time=DatepickerSplitDateTimeWidget,
)
def __init__(self, *args, **kwargs):
super(TimeSlotEditForm, self).__init__(*args, **kwargs)
self.fields['location'].queryset = self.instance.meeting.room_set.all()
class TimeSlotCreateForm(forms.Form):
name = forms.CharField(max_length=255)
type = forms.ModelChoiceField(queryset=TimeSlotTypeName.objects.all(), initial='regular')
days = forms.TypedMultipleChoiceField(
label='Meeting days',
widget=forms.CheckboxSelectMultiple,
coerce=lambda s: datetime.date.fromordinal(int(s)),
empty_value=None,
required=False
)
other_date = DatepickerDateField(
required=False,
help_text='Optional date outside the official meeting dates',
date_format="yyyy-mm-dd",
picker_settings={"autoclose": "1"},
)
time = forms.TimeField(
help_text='Time to create timeslot on each selected date',
widget=forms.TimeInput(dict(placeholder='HH:MM'))
)
duration = TimeSlotDurationField()
show_location = forms.BooleanField(required=False, initial=True)
locations = ModelMultipleChoiceField(
queryset=Room.objects.none(),
widget=forms.CheckboxSelectMultiple,
)
def __init__(self, meeting, *args, **kwargs):
super(TimeSlotCreateForm, self).__init__(*args, **kwargs)
meeting_days = [
meeting.date + datetime.timedelta(days=n)
for n in range(meeting.days)
]
# Fill in dynamic field properties
self.fields['days'].choices = self._day_choices(meeting_days)
self.fields['other_date'].widget.attrs['data-date-default-view-date'] = meeting.date
self.fields['other_date'].widget.attrs['data-date-dates-disabled'] = ','.join(
d.isoformat() for d in meeting_days
)
self.fields['locations'].queryset = meeting.room_set.order_by('name')
def clean_other_date(self):
# Because other_date is not required, failed field validation does not automatically
# invalidate the form. It should, otherwise a typo may be silently ignored.
if self.data.get('other_date') and not self.cleaned_data.get('other_date'):
raise ValidationError('Enter a valid date or leave field blank.')
return self.cleaned_data.get('other_date', None)
def clean(self):
# Merge other_date and days fields
try:
other_date = self.cleaned_data.pop('other_date')
except KeyError:
other_date = None
self.cleaned_data['days'] = self.cleaned_data.get('days') or []
if other_date is not None:
self.cleaned_data['days'].append(other_date)
if len(self.cleaned_data['days']) == 0:
self.add_error('days', ValidationError('Please select a day or specify a date'))
@staticmethod
def _day_choices(days):
"""Generates an iterable of value, label pairs for a choice field
Uses toordinal() to represent dates - would prefer to use isoformat(),
but fromisoformat() is not available in python 3.6..
"""
choices = [
(str(day.toordinal()), day.strftime('%A ({})'.format(day.isoformat())))
for day in days
]
return choices
class DurationChoiceField(forms.ChoiceField):
def __init__(self, durations=None, *args, **kwargs):
if durations is None:
durations = (3600, 5400, 7200)
super().__init__(
choices=self._make_choices(durations),
*args, **kwargs,
)
def prepare_value(self, value):
"""Converts incoming value into string used for the option value"""
if value:
return str(int(value.total_seconds())) if isinstance(value, datetime.timedelta) else str(value)
return ''
def to_python(self, value):
if value in self.empty_values or (isinstance(value, str) and not value.isnumeric()):
return None # treat non-numeric values as empty
else:
# noinspection PyTypeChecker
return datetime.timedelta(seconds=round(float(value)))
def valid_value(self, value):
return super().valid_value(self.prepare_value(value))
def _format_duration_choice(self, dur):
seconds = int(dur.total_seconds()) if isinstance(dur, datetime.timedelta) else int(dur)
hours = int(seconds / 3600)
minutes = round((seconds - 3600 * hours) / 60)
hr_str = '{} hour{}'.format(hours, '' if hours == 1 else 's')
min_str = '{} minute{}'.format(minutes, '' if minutes == 1 else 's')
if hours > 0 and minutes > 0:
time_str = ' '.join((hr_str, min_str))
elif hours > 0:
time_str = hr_str
else:
time_str = min_str
return (str(seconds), time_str)
def _make_choices(self, durations):
return (
('','--Please select'),
*[self._format_duration_choice(dur) for dur in durations])
def _set_durations(self, durations):
self.choices = self._make_choices(durations)
durations = property(None, _set_durations)
class SessionDetailsForm(forms.ModelForm):
requested_duration = DurationChoiceField()
def __init__(self, group, *args, **kwargs):
session_purposes = group.features.session_purposes
# Default to the first allowed session_purposes. Do not do this if we have an instance,
# though, because ModelForm will override instance data with initial data if it gets both.
# When we have an instance we want to keep its value.
if 'instance' not in kwargs:
kwargs.setdefault('initial', {})
kwargs['initial'].setdefault(
'purpose',
session_purposes[0] if len(session_purposes) > 0 else None,
)
kwargs['initial'].setdefault('has_onsite_tool', group.features.acts_like_wg)
super().__init__(*args, **kwargs)
self.fields['type'].widget.attrs.update({
'data-allowed-options': json.dumps({
purpose.slug: list(purpose.timeslot_types)
for purpose in SessionPurposeName.objects.all()
}),
})
self.fields['purpose'].queryset = SessionPurposeName.objects.filter(pk__in=session_purposes)
if not group.features.acts_like_wg:
self.fields['requested_duration'].durations = [datetime.timedelta(minutes=m) for m in range(30, 241, 30)]
# add bootstrap classes
self.fields['purpose'].widget.attrs.update({'class': 'form-select'})
self.fields['type'].widget.attrs.update({'class': 'form-select', 'aria-label': 'session type'})
class Meta:
model = Session
fields = (
'purpose', 'name', 'short', 'type', 'requested_duration',
'on_agenda', 'agenda_note', 'has_onsite_tool', 'chat_room', 'remote_instructions',
'attendees', 'comments',
)
labels = {'requested_duration': 'Length'}
def clean(self):
super().clean()
# Fill in on_agenda. If this is a new instance or we have changed its purpose, then use
# the on_agenda value for the purpose. Otherwise, keep the value of an existing instance (if any)
# or leave it blank.
if 'purpose' in self.cleaned_data and (
self.instance.pk is None or (self.instance.purpose != self.cleaned_data['purpose'])
):
self.cleaned_data['on_agenda'] = self.cleaned_data['purpose'].on_agenda
elif self.instance.pk is not None:
self.cleaned_data['on_agenda'] = self.instance.on_agenda
return self.cleaned_data
class Media:
js = ('ietf/js/session_details_form.js',)
class SessionEditForm(SessionDetailsForm):
"""Form to edit an existing session"""
def __init__(self, instance, *args, **kwargs):
kw_group = kwargs.pop('group', None)
if kw_group is not None and kw_group != instance.group:
raise ValueError('Session group does not match group keyword')
super().__init__(instance=instance, group=instance.group, *args, **kwargs)
class SessionCancelForm(forms.Form):
confirmed = forms.BooleanField(
label='Cancel session?',
help_text='Confirm that you want to cancel this session.',
)
class SessionDetailsInlineFormSet(forms.BaseInlineFormSet):
def __init__(self, group, meeting, queryset=None, *args, **kwargs):
self._meeting = meeting
# Restrict sessions to the meeting and group. The instance
# property handles one of these for free.
kwargs['instance'] = group
if queryset is None:
queryset = Session._default_manager
if self._meeting.pk is not None:
queryset = queryset.filter(meeting=self._meeting)
else:
queryset = queryset.none()
kwargs['queryset'] = queryset.not_deleted()
kwargs.setdefault('form_kwargs', {})
kwargs['form_kwargs'].update({'group': group})
super().__init__(*args, **kwargs)
def save_new(self, form, commit=True):
form.instance.meeting = self._meeting
return super().save_new(form, commit)
@property
def forms_to_keep(self):
"""Get the not-deleted forms"""
return [f for f in self.forms if f not in self.deleted_forms]
def sessiondetailsformset_factory(min_num=1, max_num=3):
return forms.inlineformset_factory(
Group,
Session,
formset=SessionDetailsInlineFormSet,
form=SessionDetailsForm,
can_delete=True,
can_order=False,
min_num=min_num,
max_num=max_num,
extra=max_num, # only creates up to max_num total
)
class SessionRequestStatusForm(forms.Form):
message = forms.CharField(widget=forms.Textarea(attrs={'rows': '3', 'cols': '80'}), strip=False)
class NameModelMultipleChoiceField(ModelMultipleChoiceField):
def label_from_instance(self, name):
return name.desc
class SessionRequestForm(forms.Form):
num_session = forms.ChoiceField(
choices=NUM_SESSION_CHOICES,
label="Number of sessions")
# session fields are added in __init__()
session_time_relation = forms.ChoiceField(
choices=SESSION_TIME_RELATION_CHOICES,
required=False,
label="Time between two sessions")
attendees = forms.IntegerField(label="Number of Attendees")
# FIXME: it would cleaner to have these be
# ModelMultipleChoiceField, and just customize the widgetry, that
# way validation comes for free (applies to this CharField and the
# constraints dynamically instantiated in __init__())
joint_with_groups = forms.CharField(max_length=255, required=False)
joint_with_groups_selector = forms.ChoiceField(choices=[], required=False) # group select widget for prev field
joint_for_session = forms.ChoiceField(choices=JOINT_FOR_SESSION_CHOICES, required=False)
comments = forms.CharField(
max_length=200,
label='Special Requests',
help_text='i.e. restrictions on meeting times / days, etc. (limit 200 characters)',
required=False)
third_session = forms.BooleanField(
required=False,
help_text="Help")
resources = forms.MultipleChoiceField(
widget=forms.CheckboxSelectMultiple,
required=False,
label='Resources Requested')
bethere = SearchablePersonsField(
label="Participants who must be present",
required=False,
help_text=mark_safe('<span class="fw-bold text-danger">Do not include Area Directors and WG Chairs; the system already tracks their availability.</span>'))
timeranges = NameModelMultipleChoiceField(
widget=forms.CheckboxSelectMultiple,
required=False,
label=mark_safe('Times during which this WG can <strong>not</strong> meet:<br>Please explain any selections in Special Requests below.'),
queryset=TimerangeName.objects.all())
adjacent_with_wg = forms.ChoiceField(
required=False,
label=mark_safe('Plan session adjacent with another WG:<br>(Immediately before or after another WG, no break in between, in the same room.)'))
send_notifications = forms.BooleanField(label="Send notification emails?", required=False, initial=False)
def __init__(self, group, meeting, data=None, *args, **kwargs):
self.hidden = kwargs.pop('hidden', False)
self.notifications_optional = kwargs.pop('notifications_optional', False)
self.group = group
formset_class = sessiondetailsformset_factory(max_num=3 if group.features.acts_like_wg else 50)
self.session_forms = formset_class(group=self.group, meeting=meeting, data=data)
super().__init__(data=data, *args, **kwargs)
if not self.notifications_optional:
self.fields['send_notifications'].widget = forms.HiddenInput()
# Allow additional sessions for non-wg-like groups
if not self.group.features.acts_like_wg:
self.fields['num_session'].choices = ((n, str(n)) for n in range(1, 51))
self._add_widget_class(self.fields['third_session'].widget, 'form-check-input')
self.fields['comments'].widget = forms.Textarea(attrs={'rows': '3', 'cols': '65'})
other_groups = list(allowed_conflicting_groups().exclude(pk=group.pk).values_list('acronym', 'acronym').order_by('acronym'))
self.fields['adjacent_with_wg'].choices = [('', '--No preference')] + other_groups
group_acronym_choices = [('', '--Select WG(s)')] + other_groups
self.fields['joint_with_groups_selector'].choices = group_acronym_choices
# Set up constraints for the meeting
self._wg_field_data = []
for constraintname in meeting.group_conflict_types.all():
# two fields for each constraint: a CharField for the group list and a selector to add entries
constraint_field = forms.CharField(max_length=255, required=False)
constraint_field.widget.attrs['data-slug'] = constraintname.slug
constraint_field.widget.attrs['data-constraint-name'] = str(constraintname).title()
constraint_field.widget.attrs['aria-label'] = f'{constraintname.slug}_input'
self._add_widget_class(constraint_field.widget, 'wg_constraint')
self._add_widget_class(constraint_field.widget, 'form-control')
selector_field = forms.ChoiceField(choices=group_acronym_choices, required=False)
selector_field.widget.attrs['data-slug'] = constraintname.slug # used by onchange handler
self._add_widget_class(selector_field.widget, 'wg_constraint_selector')
self._add_widget_class(selector_field.widget, 'form-control')
cfield_id = 'constraint_{}'.format(constraintname.slug)
cselector_id = 'wg_selector_{}'.format(constraintname.slug)
# keep an eye out for field name conflicts
log.assertion('cfield_id not in self.fields')
log.assertion('cselector_id not in self.fields')
self.fields[cfield_id] = constraint_field
self.fields[cselector_id] = selector_field
self._wg_field_data.append((constraintname, cfield_id, cselector_id))
# Show constraints that are not actually used by the meeting so these don't get lost
self._inactive_wg_field_data = []
inactive_cnames = ConstraintName.objects.filter(
is_group_conflict=True # Only collect group conflicts...
).exclude(
meeting=meeting # ...that are not enabled for this meeting...
).filter(
constraint__source=group, # ...but exist for this group...
constraint__meeting=meeting, # ... at this meeting.
).distinct()
for inactive_constraint_name in inactive_cnames:
field_id = 'delete_{}'.format(inactive_constraint_name.slug)
self.fields[field_id] = forms.BooleanField(required=False, label='Delete this conflict', help_text='Delete this inactive conflict?')
self._add_widget_class(self.fields[field_id].widget, 'form-control')
constraints = group.constraint_source_set.filter(meeting=meeting, name=inactive_constraint_name)
self._inactive_wg_field_data.append(
(inactive_constraint_name,
' '.join([c.target.acronym for c in constraints]),
field_id)
)
self.fields['joint_with_groups_selector'].widget.attrs['onchange'] = "document.form_post.joint_with_groups.value=document.form_post.joint_with_groups.value + ' ' + this.options[this.selectedIndex].value; return 1;"
self.fields["resources"].choices = [(x.pk, x.desc) for x in ResourceAssociation.objects.filter(name__used=True).order_by('name__order')]