class ControllerMultipleChoiceForm(forms.Form): controllers = forms.ModelMultipleChoiceField(queryset=ControllerService.get_none(), widget=CheckboxSelectMultiple) door_id = forms.IntegerField(widget=forms.HiddenInput)
class UserForm(forms.ModelForm): is_staff = forms.BooleanField(required=False, label=_("Staff user")) is_grade_publisher = forms.BooleanField(required=False, label=_("Grade publisher")) is_reviewer = forms.BooleanField(required=False, label=_("Reviewer")) courses_participating_in = forms.ModelMultipleChoiceField( None, required=False, label=_("Courses participating in (active semester)")) class Meta: model = UserProfile fields = ('username', 'title', 'first_name', 'last_name', 'email', 'delegates', 'cc_users') field_classes = { 'delegates': UserModelMultipleChoiceField, 'cc_users': UserModelMultipleChoiceField, } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) courses_in_active_semester = Course.objects.filter( semester=Semester.active_semester()) excludes = [ x.id for x in courses_in_active_semester if x.is_single_result ] courses_in_active_semester = courses_in_active_semester.exclude( id__in=excludes) self.fields[ 'courses_participating_in'].queryset = courses_in_active_semester if self.instance.pk: self.fields[ 'courses_participating_in'].initial = courses_in_active_semester.filter( participants=self.instance) self.fields['is_staff'].initial = self.instance.is_staff self.fields[ 'is_grade_publisher'].initial = self.instance.is_grade_publisher self.fields['is_reviewer'].initial = self.instance.is_reviewer def clean_username(self): username = self.cleaned_data.get('username') user_with_same_name = UserProfile.objects.filter( username__iexact=username) # make sure we don't take the instance itself into account if self.instance and self.instance.pk: user_with_same_name = user_with_same_name.exclude( pk=self.instance.pk) if user_with_same_name.exists(): raise forms.ValidationError( _("A user with the username '%s' already exists") % username) return username.lower() def clean_email(self): email = self.cleaned_data.get('email') if email is None: return user_with_same_email = UserProfile.objects.filter(email__iexact=email) # make sure we don't take the instance itself into account if self.instance and self.instance.pk: user_with_same_email = user_with_same_email.exclude( pk=self.instance.pk) if user_with_same_email.exists(): raise forms.ValidationError( _("A user with the email '%s' already exists") % email) return email.lower() def save(self, *args, **kw): super().save(*args, **kw) new_course_list = list( self.instance.courses_participating_in.exclude( semester=Semester.active_semester())) + list( self.cleaned_data.get('courses_participating_in')) self.instance.courses_participating_in.set(new_course_list) staff_group = Group.objects.get(name="Staff") grade_publisher_group = Group.objects.get(name="Grade publisher") reviewer_group = Group.objects.get(name="Reviewer") if self.cleaned_data.get('is_staff'): self.instance.groups.add(staff_group) else: self.instance.groups.remove(staff_group) if self.cleaned_data.get('is_grade_publisher'): self.instance.groups.add(grade_publisher_group) else: self.instance.groups.remove(grade_publisher_group) if self.cleaned_data.get( 'is_reviewer') and not self.cleaned_data.get('is_staff'): self.instance.groups.add(reviewer_group) else: self.instance.groups.remove(reviewer_group)
class DeviceTagForm(forms.Form): error_css_class = 'has-error' tags = forms.ModelMultipleChoiceField( Devicetag.objects.all(), widget=forms.SelectMultiple(attrs={"style": "width:100%;"})) device = forms.ModelChoiceField(Device.objects.all())
class EmailDistributionForm(forms.ModelForm): recipient_choices = forms.ModelMultipleChoiceField( queryset=None, widget=forms.CheckboxSelectMultiple) class Meta: model = DistributionEmail fields = ['subject'] def __init__(self, *args, **kwargs): self.distribution = kwargs.pop('distribution') super().__init__(*args, **kwargs) if not EmailAddressee.objects.count(): email_addressee_start_values = [ ('Hospitalists', '*****@*****.**', True, True), ('Cheryl', '*****@*****.**', True, True), ('Susan', '*****@*****.**', True, True), ('Intensivists', '*****@*****.**', True, False), ('ID docs', '*****@*****.**', True, False) ] for (displayed_name, email_address, visible, pre_checked) in email_addressee_start_values: EmailAddressee.objects.get_or_create( displayed_name=displayed_name, email_address=email_address, visible=visible, pre_checked=pre_checked)[0] self.fields[ 'recipient_choices'].queryset = EmailAddressee.objects.filter( visible=True) self.initial['recipient_choices'] = EmailAddressee.objects.filter( pre_checked=True) instance = self.instance instance.distribution = self.distribution if self.distribution.date == timezone.localdate(): self.initial[ 'subject'] = f'Pt Assignment - {self.distribution.date.strftime("%a %m/%d/%y")}' else: self.initial['subject'] = f'Pt Assignment for {self.distribution.date.strftime("%a %m/%d/%y")} ' + \ f'sent on {timezone.localtime().strftime("%a %m/%d/%y")}' instance.html_message = render_to_string( 'distribution/simple_assignment_table.html', instance.assemble_pt_assignment_context()) # instance.save() self.helper = FormHelper() self.helper.form_id = 'id_email_distribution_form' self.helper.form_method = 'post' self.helper.layout = Layout( Div( HTML('<h5>Subject:</h5>'), Field('subject', wrapper_class='subject-field ml-5'), css_class='form-row subject-textbox', ), HTML('<h5>To:</h5>'), Div(Field('recipient_choices', wrapper_class='recipient_field ml-5', css_class='position-static'), css_class='form-row recipient-checkboxes'), Div(Submit('submit', 'Send Email', css_id='id_email_patient_distribution', css_class='btn-primary', wrapper_class='text-center'), css_class='text-center')) self.helper.form_show_labels = False # self.helper.add_input( # Submit('submit', 'Send Email', css_id='id_email_patient_distribution', css_class='btn-primary', # wrapper_class='text-center')) def save(self, *args, **kwargs): instance = super().save() instance.recipient_text_field = [] for recipient_choice in self.cleaned_data['recipient_choices']: instance.recipient_text_field.append( recipient_choice.email_address) instance.save() return instance
class CourseForm(forms.ModelForm): general_questions = forms.ModelMultipleChoiceField( Questionnaire.objects.filter(is_for_contributors=False, obsolete=False), widget=CheckboxSelectMultiple, label=_("Questions about the course")) semester = forms.ModelChoiceField(Semester.objects.all(), disabled=True, required=False, widget=forms.HiddenInput()) # the following field is needed, because the auto_now=True for last_modified_time makes the corresponding field # uneditable and so it can't be displayed in the model form # see https://docs.djangoproject.com/en/dev/ref/models/fields/#datefield for details last_modified_time_2 = forms.DateTimeField(label=_("Last modified"), required=False, localize=True, disabled=True) # last_modified_user would usually get a select widget but should here be displayed as a readonly CharField instead last_modified_user_2 = forms.CharField(label=_("Last modified by"), required=False, disabled=True) class Meta: model = Course fields = ('name_de', 'name_en', 'type', 'degrees', 'is_graded', 'is_private', 'is_required_for_reward', 'vote_start_date', 'vote_end_date', 'participants', 'general_questions', 'last_modified_time_2', 'last_modified_user_2', 'semester') localized_fields = ('vote_start_date', 'vote_end_date') field_classes = { 'participants': UserModelMultipleChoiceField, } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields[ 'general_questions'].queryset = Questionnaire.objects.filter( is_for_contributors=False).filter( Q(obsolete=False) | Q(contributions__course=self.instance)).distinct() if self.instance.general_contribution: self.fields['general_questions'].initial = [ q.pk for q in self.instance.general_contribution.questionnaires.all() ] self.fields[ 'last_modified_time_2'].initial = self.instance.last_modified_time if self.instance.last_modified_user: self.fields[ 'last_modified_user_2'].initial = self.instance.last_modified_user.full_name if self.instance.state in ['in_evaluation', 'evaluated', 'reviewed']: self.fields['vote_start_date'].disabled = True if not self.instance.can_staff_edit: # form is used as read-only course view disable_all_fields(self) def clean(self): super().clean() vote_start_date = self.cleaned_data.get('vote_start_date') vote_end_date = self.cleaned_data.get('vote_end_date') if vote_start_date and vote_end_date: if vote_start_date >= vote_end_date: self.add_error("vote_start_date", "") self.add_error( "vote_end_date", _("The first day of evaluation must be before the last one." )) def save(self, user, *args, **kw): self.instance.last_modified_user = user super().save(*args, **kw) self.instance.general_contribution.questionnaires.set( self.cleaned_data.get('general_questions')) logger.info( 'Course "{}" (id {}) was edited by staff member {}.'.format( self.instance, self.instance.id, user.username))
class ScanForm(BaseForm): scan_map = forms.ModelMultipleChoiceField( Map.objects.all(), widget=autocomplete.ModelSelect2Multiple( url='maps-ac:map-autocomplete', attrs={ 'data-placeholder': ugettext_lazy('Type for getting available entries') }), required=False) scan_person = forms.ModelMultipleChoiceField( Person.objects.all(), required=False, widget=autocomplete.ModelSelect2Multiple( url='maps-ac:persons-autocomplete', attrs={ 'data-placeholder': ugettext_lazy('Type for getting available entries') })) scan_reference = forms.ModelMultipleChoiceField( Reference.objects.all(), required=False, widget=autocomplete.ModelSelect2Multiple( url='maps-ac:references-autocomplete', attrs={ 'data-placeholder': ugettext_lazy('Type for getting available entries') })) class Meta: model = Scan fields = ('name', 'info', 'scan_date', 'scan_type', 'file', 'scan_map', 'scan_person', 'scan_reference') widgets = { 'scan_date': forms.DateInput(format='%Y-%m-%d', attrs={ 'class': 'date', 'input_formats': '%Y-%m-%d', 'placeholder': 'YYYY-MM-DD' }) } def __init__(self, *args, **kwargs): super(ScanForm, self).__init__(*args, **kwargs) instance = kwargs.get('instance') self.helper = FormHelper() self.helper.add_input(Submit('submit', ugettext('submit').capitalize())) selected_ids = [o.id for o in instance.scan_type.all()] if instance else [] nodes_html = self.get_nodes_html( Type.objects.get(name='Scan', parent=None), selected_ids) self.fields['scan_map'].label = 'Map title' if instance and instance.pk: self.fields['file'].widget.attrs['disabled'] = True self.helper.layout = Layout( Div(HTML('<div class="form-header">' + ugettext('data').capitalize() + '</div>'), 'name', 'scan_date', 'scan_map', 'scan_reference', 'scan_person', css_class='form-float'), Div( HTML('<div class="form-header">' + ugettext('types').capitalize() + '</div>'), HTML(nodes_html), HTML('<div style="clear:both;"></div>'), 'info'), Div('scan_type', 'file', css_class='hidden')) else: self.helper.layout = Layout( Div(HTML('<div class="form-header">' + ugettext('data').capitalize() + '</div>'), 'file', HTML('<p>' + ugettext('Max file size') + ': ' + filesizeformat(settings.ALLOWED_SCAN_SIZE) + '<br />' + ugettext('allowed files') + ': ' + ', '.join(settings.ALLOWED_SCAN_EXTENSIONS) + '</p>'), 'name', 'scan_date', 'scan_map', 'scan_reference', 'scan_person', css_class='form-float'), Div( HTML('<div class="form-header">' + ugettext('types').capitalize() + '</div>'), HTML(nodes_html), HTML('<div style="clear:both;"></div>'), 'info'), Div('scan_type', css_class='hidden'), Div( HTML(''' <script> $(document).ready(function () {{ $('#id_file').on("change", function() {{ /* check and warn if filesize is too big */ if ($('#id_file')[0].files[0].size > {allowed_upload_size}) {{ alert('{file_too_big_error}') }} /* if name is empty, fill with filename without the extension */ if ($('#id_name').val() == '') {{ var filename = $('#id_file')[0].files.length ? $('#id_file')[0].files[0].name : ''; $('#id_name').val(filename.replace(/\.[^/.]+$/, "")); }} }}); }}); </script>'''.format( allowed_upload_size=settings.ALLOWED_SCAN_SIZE, file_too_big_error=ugettext( 'This file is too big.')))))
class ContractDataForm(TranslatableModelForm): producers = forms.ModelMultipleChoiceField( Producer.objects.filter(is_active=True), label=_('Producers'), widget=admin.widgets.FilteredSelectMultiple(_('Producers'), False), required=True)
class MultiUserChooseForm(forms.Form): users = forms.ModelMultipleChoiceField(User.objects.active().buyers(), required=True)
class ExperimentOverviewForm(ChangeLogMixin, forms.ModelForm): type = forms.ChoiceField(label="Type", choices=Experiment.TYPE_CHOICES, help_text=Experiment.TYPE_HELP_TEXT) owner = forms.ModelChoiceField( required=True, label="Delivery Owner", help_text=Experiment.OWNER_HELP_TEXT, queryset=get_user_model().objects.all().order_by("email"), # This one forces the <select> widget to not include a blank # option which would otherwise be included because the model field # is nullable. empty_label=None, ) name = forms.CharField(label="Name", help_text=Experiment.NAME_HELP_TEXT) slug = forms.CharField(required=False, widget=forms.HiddenInput()) short_description = forms.CharField( label="Description", help_text=Experiment.SHORT_DESCRIPTION_HELP_TEXT, widget=forms.Textarea(attrs={"rows": 3}), ) public_name = forms.CharField(required=False, label="Public Name", help_text=Experiment.PUBLIC_NAME_HELP_TEXT) public_description = forms.CharField( required=False, label="Public Description", help_text=Experiment.PUBLIC_DESCRIPTION_HELP_TEXT, widget=forms.Textarea(attrs={"rows": 3}), ) data_science_bugzilla_url = BugzillaURLField( required=False, label="Data Science Bugzilla URL", help_text=Experiment.DATA_SCIENCE_BUGZILLA_HELP_TEXT, ) engineering_owner = forms.CharField( required=False, label="Engineering Owner", help_text=Experiment.ENGINEERING_OWNER_HELP_TEXT, ) analysis_owner = forms.ModelChoiceField( required=False, label="Data Science Owner", help_text=Experiment.ANALYSIS_OWNER_HELP_TEXT, queryset=get_user_model().objects.all().order_by("email"), # This one forces the <select> widget to not include a blank # option which would otherwise be included because the model field # is nullable. empty_label="Data Science Owner", ) feature_bugzilla_url = BugzillaURLField( required=False, label="Feature Bugzilla URL", help_text=Experiment.FEATURE_BUGZILLA_HELP_TEXT, ) related_work = forms.CharField( required=False, label="Related Work URLs", help_text=Experiment.RELATED_WORK_HELP_TEXT, widget=forms.Textarea(attrs={"rows": 3}), ) related_to = forms.ModelMultipleChoiceField( label="Related Deliveries", required=False, help_text="Is this related to a previously run delivery?", queryset=Experiment.objects.all(), ) class Meta: model = Experiment fields = [ "type", "owner", "name", "slug", "short_description", "public_name", "public_description", "data_science_bugzilla_url", "analysis_owner", "engineering_owner", "feature_bugzilla_url", "related_work", "related_to", ] related_to.widget.attrs.update({"data-live-search": "true"}) def clean_name(self): name = self.cleaned_data["name"] slug = slugify(name) if not slug: raise forms.ValidationError( "This name must include non-punctuation characters.") if (self.instance.pk is None and slug and self.Meta.model.objects.filter(slug=slug).exists()): raise forms.ValidationError("This name is already in use.") return name def clean(self): cleaned_data = super().clean() if self.instance.slug: del cleaned_data["slug"] else: name = cleaned_data.get("name") cleaned_data["slug"] = slugify(name) if cleaned_data["type"] != ExperimentConstants.TYPE_ROLLOUT: required_msg = "This field is required." required_fields = ( "data_science_bugzilla_url", "public_name", "public_description", ) for required_field in required_fields: if (not cleaned_data.get(required_field) and required_field not in self._errors): self._errors[required_field] = [required_msg] return cleaned_data
class StockBulkDeleteForm(forms.Form): items = forms.ModelMultipleChoiceField(queryset=Stock.objects) def delete(self): items = Stock.objects.filter(pk__in=self.cleaned_data['items']) items.delete()
class BasicTestingReportFormFields(forms.Form): """Testing report form with basic necessary fields""" r_product = ModelChoiceField( required=True, label='Product', empty_label=None, queryset=Product.objects.only('name').order_by('name'), error_messages={ 'required': 'You have to select a product to generate this ' 'testing report.', 'invalid_choice': '%(value)s is not a valid product.', }, widget=forms.Select(attrs={ 'id': 'r_product', })) r_build = forms.ModelMultipleChoiceField( required=False, label='Build', queryset=TestBuild.objects.none(), error_messages={ 'invalid_pk_value': '%s is not a valid test build ID.', 'invalid_choice': 'Test build ID %s does not exist.', }, widget=forms.SelectMultiple(attrs={ 'id': 'r_build', 'size': '5', })) r_version = forms.ModelMultipleChoiceField( required=False, label='Version', queryset=Version.objects.none(), error_messages={ 'invalid_choice': 'Version ID %s does not exist.', 'invalid_pk_value': '%s is not a valid version ID.', }, widget=forms.SelectMultiple(attrs={ 'id': 'r_version', 'size': '5', })) r_created_since = forms.DateField( required=False, input_formats=['%Y-%m-%d'], error_messages={ 'invalid': 'The start execute date is invalid. The valid format' ' is YYYY-MM-DD.', }, widget=forms.TextInput(attrs={ 'id': 'r_created_since', 'style': 'width:130px;', 'class': 'vDateField', })) r_created_before = forms.DateField( required=False, input_formats=['%Y-%m-%d'], error_messages={ 'invalid': 'The end execute date is invalid. The valid format ' 'is YYYY-MM-DD.', }, widget=forms.TextInput(attrs={ 'id': 'r_created_before', 'style': 'width:130px;', 'class': 'vDateField', })) def populate(self, product_id): if product_id: self.fields['r_build'].queryset = TestBuild.objects.filter( product=product_id).only('name') self.fields['r_version'].queryset = Version.objects.filter( product=product_id).only('value') else: self.fields['r_build'].queryset = TestBuild.objects.none() self.fields['r_version'].queryset = Version.objects.none()
class BattleSheet(forms.Form): """Form for the battle tab of the character sheet, used to help save any updated information.""" char_level = forms.IntegerField(required=False, disabled=True) # Ability Scores: STR = forms.IntegerField(required=False, disabled=True) DEX = forms.IntegerField(required=False, disabled=True) CON = forms.IntegerField(required=False, disabled=True) INT = forms.IntegerField(required=False, disabled=True) WIS = forms.IntegerField(required=False, disabled=True) CHA = forms.IntegerField(required=False, disabled=True) # Saving Throws: STR_ST = forms.BooleanField(required=False, disabled=True) DEX_ST = forms.BooleanField(required=False, disabled=True) CON_ST = forms.BooleanField(required=False, disabled=True) INT_ST = forms.BooleanField(required=False, disabled=True) WIS_ST = forms.BooleanField(required=False, disabled=True) CHA_ST = forms.BooleanField(required=False, disabled=True) # Skills: acrobatics = forms.BooleanField( required=False, disabled=True, widget=forms.CheckboxInput(attrs={'data-skill': 'acrobatics'})) animal = forms.BooleanField( required=False, disabled=True, widget=forms.CheckboxInput(attrs={'data-skill': 'animal'})) arcana = forms.BooleanField( required=False, disabled=True, widget=forms.CheckboxInput(attrs={'data-skill': 'arcana'})) athletics = forms.BooleanField( required=False, disabled=True, widget=forms.CheckboxInput(attrs={'data-skill': 'athletics'})) deception = forms.BooleanField( required=False, disabled=True, widget=forms.CheckboxInput(attrs={'data-skill': 'deception'})) history = forms.BooleanField( required=False, disabled=True, widget=forms.CheckboxInput(attrs={'data-skill': 'history'})) insight = forms.BooleanField( required=False, disabled=True, widget=forms.CheckboxInput(attrs={'data-skill': 'insight'})) intimidation = forms.BooleanField( required=False, disabled=True, widget=forms.CheckboxInput(attrs={'data-skill': 'intimidation'})) investigation = forms.BooleanField( required=False, disabled=True, widget=forms.CheckboxInput(attrs={'data-skill': 'investigation'})) medicine = forms.BooleanField( required=False, disabled=True, widget=forms.CheckboxInput(attrs={'data-skill': 'medicine'})) nature = forms.BooleanField( required=False, disabled=True, widget=forms.CheckboxInput(attrs={'data-skill': 'nature'})) perception = forms.BooleanField( required=False, disabled=True, widget=forms.CheckboxInput(attrs={'data-skill': 'perception'})) performance = forms.BooleanField( required=False, disabled=True, widget=forms.CheckboxInput(attrs={'data-skill': 'performance'})) persuasion = forms.BooleanField( required=False, disabled=True, widget=forms.CheckboxInput(attrs={'data-skill': 'persuasion'})) religion = forms.BooleanField( required=False, disabled=True, widget=forms.CheckboxInput(attrs={'data-skill': 'religion'})) sleight = forms.BooleanField( required=False, disabled=True, widget=forms.CheckboxInput(attrs={'data-skill': 'sleight'})) stealth = forms.BooleanField( required=False, disabled=True, widget=forms.CheckboxInput(attrs={'data-skill': 'stealth'})) survival = forms.BooleanField( required=False, disabled=True, widget=forms.CheckboxInput(attrs={'data-skill': 'survival'})) # Armor and Movement: ac = forms.IntegerField(required=False, disabled=True) init = forms.IntegerField(required=False, disabled=True) speed = forms.IntegerField(required=False, disabled=True) # HP and Conditions: max_hp = forms.IntegerField(required=False, disabled=True) cur_hp = forms.IntegerField(required=False, disabled=True) temp_hp = forms.IntegerField(required=False, disabled=True) hit_dice_current = forms.IntegerField(required=False, disabled=True) conditions = forms.ModelMultipleChoiceField( queryset=Condition.objects.all(), required=False, disabled=True) # Point Tracker: current_points = forms.IntegerField(required=False, disabled=True) max_points = forms.IntegerField(required=False, disabled=True) spell_slots_1_current = forms.IntegerField(required=False, disabled=True) spell_slots_2_current = forms.IntegerField(required=False, disabled=True) spell_slots_3_current = forms.IntegerField(required=False, disabled=True) spell_slots_4_current = forms.IntegerField(required=False, disabled=True) spell_slots_5_current = forms.IntegerField(required=False, disabled=True) spell_slots_6_current = forms.IntegerField(required=False, disabled=True) spell_slots_7_current = forms.IntegerField(required=False, disabled=True) spell_slots_8_current = forms.IntegerField(required=False, disabled=True) spell_slots_9_current = forms.IntegerField(required=False, disabled=True) spell_slots_1_maximum = forms.IntegerField(required=False, disabled=True) spell_slots_2_maximum = forms.IntegerField(required=False, disabled=True) spell_slots_3_maximum = forms.IntegerField(required=False, disabled=True) spell_slots_4_maximum = forms.IntegerField(required=False, disabled=True) spell_slots_5_maximum = forms.IntegerField(required=False, disabled=True) spell_slots_6_maximum = forms.IntegerField(required=False, disabled=True) spell_slots_7_maximum = forms.IntegerField(required=False, disabled=True) spell_slots_8_maximum = forms.IntegerField(required=False, disabled=True) spell_slots_9_maximum = forms.IntegerField(required=False, disabled=True)
class BaseEventForm(ModelForm): """ Form used in creating or editing event objects. This only creates the event itself, not the shifts, though the formset for creating those is often paired with this. """ TWEET_CHOICES = ( ('N', 'No Tweet'), ('T', 'Tweet normally'), ('H', 'Tweet with #UmichEngin'), ) leaders = forms.ModelMultipleChoiceField( widget=Select2MultipleWidget(), queryset=MemberProfile.get_members()) tweet_option = forms.ChoiceField(choices=TWEET_CHOICES, initial='N') agenda = forms.ModelChoiceField( widget=Select2Widget(), queryset=MeetingMinutes.objects.filter( semester=AcademicTerm.get_current_term(), meeting_type__in=['NI', 'MM']), required=False, ) class Meta: model = CalendarEvent fields = [ 'name', 'term', 'event_type', 'event_class', 'description', 'agenda', 'google_cal', 'leaders', 'assoc_officer', 'announce_start', 'announce_text', 'preferred_items', 'min_unsign_up_notice', 'min_sign_up_notice', 'members_only', 'needs_carpool', 'use_sign_in', 'allow_advance_sign_up', 'needs_facebook_event', 'needs_flyer', 'requires_UM_background_check', 'requires_AAPS_background_check', 'mutually_exclusive_shifts', 'allow_overlapping_sign_ups', 'needs_COE_event', ] def clean(self): """ Ensures that tweets are not sent or COE events not created for events which are marked as members-only """ cleaned_data = super(BaseEventForm, self).clean() members_only = cleaned_data.get('members_only') tweet_option = cleaned_data.get('tweet_option') coe_option = cleaned_data.get('needs_COE_event') if members_only and not tweet_option == 'N': raise ValidationError( _('Tweeting is not currentlys supported' ' for members-only events')) if members_only and coe_option: raise ValidationError( _('Members-only events cannot be on the' ' COE Calendar.')) return cleaned_data
class PurchaseDiscountForm(forms.Form): code = forms.CharField( required=True, max_length=100, min_length=4, help_text='Enter the code you want to use to provide the discount.') amount = forms.IntegerField(required=False, initial=0, label="Fixed discount in {0}".format( settings.CURRENCY_ABBREV), validators=[ MinValueValidator(0), ]) percent = forms.IntegerField(required=False, initial=0, label="Percent discount", validators=[ MinValueValidator(0), MaxValueValidator(100), ]) maxuses = forms.IntegerField(required=True, initial=1, label="Maximum uses", validators=[ MinValueValidator(1), MaxValueValidator(30), ]) expires = forms.DateField(required=True, label="Expiry date") requiredoptions = forms.ModelMultipleChoiceField( required=False, queryset=None, label="Required options", widget=Bootstrap4CheckboxSelectMultiple, help_text= "Check any additional options that are required. Registrations without those options will not be able to use the discount code." ) confirm = forms.BooleanField( help_text= "Check this form to confirm that you will pay the costs generated by the people using this code, as specified by the invoice." ) def __init__(self, conference, showconfirm=False, *args, **kwargs): self.conference = conference super(PurchaseDiscountForm, self).__init__(*args, **kwargs) self.fields[ 'requiredoptions'].queryset = ConferenceAdditionalOption.objects.filter( conference=conference, public=True) self.fields['expires'].initial = conference.startdate - timedelta( days=2) self.fields['expires'].validators.append( BeforeValidator(conference.startdate - timedelta(days=1))) self.fields['expires'].validators.append( AfterValidator(date.today() - timedelta(days=1))) if not showconfirm: del self.fields['confirm'] def clean_code(self): # Check if code is already in use for this conference if DiscountCode.objects.filter( conference=self.conference, code=self.cleaned_data['code'].upper()).exists(): raise ValidationError( "This discount code is already in use for this conference") # Force to uppercase. CSS takes care of that at the presentation layer return self.cleaned_data['code'].upper() def clean(self): cleaned_data = super(PurchaseDiscountForm, self).clean() if 'amount' in cleaned_data and 'percent' in cleaned_data: # Only one can be specified if _int_with_default(cleaned_data['amount'], 0) > 0 and _int_with_default( cleaned_data['percent'], 0) > 0: self._errors['amount'] = ErrorList( ['Cannot specify both amount and percent!']) self._errors['percent'] = ErrorList( ['Cannot specify both amount and percent!']) elif _int_with_default(cleaned_data['amount'], 0) == 0 and _int_with_default( cleaned_data['percent'], 0) == 0: self._errors['amount'] = ErrorList( ['Must specify amount or percent!']) self._errors['percent'] = ErrorList( ['Must specify amount or percent!']) return cleaned_data
class CreateCourseForm(forms.ModelForm): """ Form used for a user to create a course Attributes (Fields): name: [CharField] Course name field info: [CharField] Course information field term: [ChoiceField] List of possible terms slug: [CharField] Course slug students: [ModelMultipleChoiceField] List of students Methods: __init__ : Initializes form, filtering querysets for fields """ #Filters queryset based on conditions def __init__(self, uid, *args, **kwargs): super(CreateCourseForm, self).__init__(*args, **kwargs) #Renders slug as HiddenInput if 'instance' in kwargs: self.fields['slug'].widget = forms.HiddenInput() self.fields['term'].widget = forms.HiddenInput() else: self.fields['students'].widget = forms.HiddenInput() self.fields['limit_interest'].widget = forms.HiddenInput() self.fields['name'].validators.append(ForbiddenNamesValidator) #course name field name = forms.CharField( #Text input widget=forms.TextInput(attrs={'class': 'form-control'}), #With length 255 max_length=255, #Field required required=True) #course info field info = forms.CharField( #Text input widget=forms.TextInput(attrs={'class': 'form-control'}), #With length 255 max_length=255, #Field Required required=True) #Term field term = forms.ChoiceField( #Choices from Term_Choice choices=Term_Choice, #Field Required required=True) #Slug Field slug = forms.CharField( #Text Input widget=forms.TextInput(attrs={'class': 'form-control'}), #With Length 20 max_length=20, #Field NOT Required required=False) #Students field students = forms.ModelMultipleChoiceField( #Multiple Choice Selection widget=forms.CheckboxSelectMultiple, #From all user objects queryset=User.objects.all(), #Field NOT Required required=False) #Field for only professor creating courses limit_creation = forms.BooleanField( #Initially field is false initial=False, #Labeled as "Only professor can create projects?" label='Only Professor can create projects?', #Field NOT Required required=False) limit_weights = forms.BooleanField( label="Limit projects to only use specified weights for matches", required=False) weigh_interest = forms.IntegerField( min_value=0, max_value=5, label="Weight of user interest in project", required=False) weigh_know = forms.IntegerField( min_value=0, max_value=5, label="Weight of skills users already know", required=False) weigh_learn = forms.IntegerField( min_value=0, max_value=5, label="Weight of skills users want to learn", required=False) csv_file = forms.FileField(required=False, label="Upload a CSV Roster") # lower_time_bound = forms.ChoiceField( # label="Custom Lower Time Boundary for Scheduling", # #Choices from Lower_Boundary_Choice # choices=Lower_Boundary_Choice, # #Field Required # required=False) # upper_time_bound = forms.ChoiceField( # label="Custom Upper Time Boundary for Scheduling", # #Choices from Upper_Boundary_Choice # choices=Upper_Boundary_Choice, # #Field Required # required=False) limit_interest = forms.BooleanField( label="Disable ability for students to show interest in projects", required=False) csv_file = forms.FileField(required=False, label="Upload a CSV Roster") #META CLASS class Meta: model = Course fields = [ 'name', 'info', 'term', 'students', 'slug', 'limit_creation', 'weigh_interest', 'weigh_know', 'weigh_learn', 'limit_weights' ]
class DataRequestEditForm(forms.ModelForm): ORDERED_FIELDS = ["purpose", "purpose_other", "data_class_requested","data_class_other"] INTENDED_USE_CHOICES = Choices( ('Disaster Risk Management', _('Disaster Risk Management')), ('Urban/Land Subdivision Planning', _('Urban/Land Subdivision Planning')), ('Road/Infrastracture Planning', _('Road/Infrastracture Planning')), ('Transport/Traffic Management', _('Transport/Traffic Management')), ('Oil/Gas/Geothermal/Quarries/Minerals Exploration', _('Oil/Gas/Geothermal/Quarries/Minerals Exploration')), ('Biological/Agricultural/Forestry/Marine/Natural Resource Planning', _('Biological/Agricultural/Forestry/Marine/Natural Resource Planning')), ('Cellular Network Mapping', _('Cellular Network Mapping')), ('other', _('Other, please specify:')), ) purpose = forms.ChoiceField( label =_(u'Purpose of the Data'), choices = INTENDED_USE_CHOICES ) purpose_other = forms.CharField( label=_(u'Your custom purpose for the data'), required=False ) data_class_requested = forms.ModelMultipleChoiceField( label = _('Types of Data Requested. (Press CTRL to select multiple types)'), queryset = TileDataClass.objects.all(), to_field_name = 'short_name', required = True ) class Meta: model = DataRequest fields = [ "project_summary", "purpose", #"data_class_requested", "data_class_other", "intended_use_of_dataset", "additional_remarks" ] def __init__(self, *args, **kwargs): super(DataRequestEditForm, self).__init__(*args, **kwargs) #self.fields.pop('letter_file') self.fields.keyOrder = self.ORDERED_FIELDS + [k for k in self.fields.keys() if k not in self.ORDERED_FIELDS] if 'initial' in kwargs: if 'data_type' in kwargs['initial']: initial_tags = [] for t_item in kwargs['initial']['data_type']: initial_tags.append(t_item.tag.name) self.fields['data_class_requested'].initial = initial_tags self.helper = FormHelper() self.helper.form_tag = False self.helper.layout = Layout( Div( Field('project_summary', css_class='form-control'), css_class='form-group' ), Div( Field('purpose', css_class='form-control'), Div( Field('purpose_other', css_class='form-control'), css_class='col-sm-11 col-sm-offset-1' ), css_class='form-group' ), Div( Field('data_class_requested', css_class='form-control'), css_class='form-group' ), Div( Field('data_class_other', css_class='form-control'), css_class='form-group' ), Div( Field('intended_use_of_dataset', css_class='form-control'), css_class='form-group' ), Div( Field('additional_remarks', css_class='form-control'), css_class='form-group' ), ) def clean_purpose_other(self): purpose = self.cleaned_data.get('purpose') purpose_other = self.cleaned_data.get('purpose_other') if purpose == self.INTENDED_USE_CHOICES.other: if not purpose_other: raise forms.ValidationError( 'Please state your purpose for the requested data.') return purpose_other def clean_purpose(self): purpose = self.cleaned_data.get('purpose') if purpose == self.INTENDED_USE_CHOICES.other: purpose_other = self.cleaned_data.get('purpose_other') if not purpose_other: return purpose else: return purpose_other return purpose def clean_data_class_other(self): data_class_other = self.cleaned_data.get('data_class_other') pprint(self.cleaned_data.get('data_class_requested')) data_classes = self.clean_data_class_requested() #data_classes = [c.short_name for c in self.cleaned_data.get('data_class_requested')]#self.cleaned_data.get('data_class_requested') if data_classes: if 'Other' in data_classes and not data_class_other: raise forms.ValidationError(_('This field is required if you selected Other')) if 'Other' not in data_classes and data_class_other: return None return data_class_other def clean_data_class_requested(self): pprint('admin edit form') data_classes = self.cleaned_data.get('data_class_requested') pprint("data_classes:"+str(data_classes)) data_class_list = [] if data_classes: for dc in data_classes: data_class_list.append(dc) return data_class_list else: raise forms.ValidationError( "Please choose the data class you want to download. If it is not in the list, select 'Other' and indicate the data class in the text box that appears")
def test_should_multiple_choice_convert_connectionorlist(): field = forms.ModelMultipleChoiceField(Reporter.objects.all()) graphene_type = convert_form_field(field) assert isinstance(graphene_type, List) assert graphene_type.of_type == ID
class AppUserEditForm(forms.ModelForm): tools_access_role_arn = forms.CharField( label="Tools access IAM role arn", help_text="The arn for the IAM role required to start local tools", required=False, widget=AdminTextInputWidget(), ) home_directory_efs_access_point_id = forms.CharField( label="Home directory ID", help_text="EFS Access Point ID", max_length=128, required=False, empty_value=None, widget=AdminTextInputWidget(), ) can_start_all_applications = forms.BooleanField( label="Can start local tools", help_text="For JupyterLab, rStudio and pgAdmin", required=False, ) can_develop_visualisations = forms.BooleanField( label="Can develop visualisations", help_text="To deploy and manage visualisations from code in Gitlab", required=False, ) can_access_appstream = forms.BooleanField(label="Can access AppStream", help_text="For SPSS and STATA", required=False) can_access_quicksight = forms.BooleanField( label="Can access QuickSight", help_text= "Note: the user must also be given separate access to AWS QuickSight via DIT SSO", required=False, ) authorized_master_datasets = forms.ModelMultipleChoiceField( required=False, widget=FilteredSelectMultiple("master datasets", False), queryset=MasterDataset.objects.live().filter( user_access_type=UserAccessType.REQUIRES_AUTHORIZATION).order_by( "name"), ) authorized_data_cut_datasets = forms.ModelMultipleChoiceField( required=False, widget=FilteredSelectMultiple("data cut datasets", False), queryset=DataCutDataset.objects.live().filter( user_access_type=UserAccessType.REQUIRES_AUTHORIZATION).order_by( "name"), ) authorized_visualisations = forms.ModelMultipleChoiceField( label="Authorized visualisations", required=False, widget=FilteredSelectMultiple("visualisations", False), queryset=None, ) class Meta: model = get_user_model() fields = "__all__" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) instance = kwargs["instance"] self.fields[ "tools_access_role_arn"].initial = instance.profile.tools_access_role_arn self.fields["tools_access_role_arn"].widget.attrs[ "class"] = "vTextField" self.fields[ "home_directory_efs_access_point_id"].initial = instance.profile.home_directory_efs_access_point_id self.fields["home_directory_efs_access_point_id"].widget.attrs[ "class"] = "vTextField" self.fields[ "can_start_all_applications"].initial = instance.user_permissions.filter( codename="start_all_applications", content_type=ContentType.objects.get_for_model( ApplicationInstance), ).exists() self.fields[ "can_develop_visualisations"].initial = instance.user_permissions.filter( codename="develop_visualisations", content_type=ContentType.objects.get_for_model( ApplicationInstance), ).exists() self.fields[ "can_access_appstream"].initial = instance.user_permissions.filter( codename="access_appstream", content_type=ContentType.objects.get_for_model( ApplicationInstance), ).exists() self.fields[ "can_access_quicksight"].initial = instance.user_permissions.filter( codename="access_quicksight", content_type=ContentType.objects.get_for_model( ApplicationInstance), ).exists() self.fields[ "authorized_master_datasets"].initial = MasterDataset.objects.live( ).filter(datasetuserpermission__user=instance) self.fields[ "authorized_data_cut_datasets"].initial = DataCutDataset.objects.live( ).filter(datasetuserpermission__user=instance) self.fields[ "authorized_visualisations"].initial = VisualisationCatalogueItem.objects.live( ).filter(visualisationuserpermission__user=instance) self.fields[ "authorized_visualisations"].queryset = VisualisationCatalogueItem.objects.live( ).order_by("name", "id")
class ChangeDealerGroupForm(forms.ModelForm): clients = forms.ModelMultipleChoiceField( required=False, widget=forms.SelectMultiple(attrs={"disabled": True}), queryset=None) class Meta: model = ChangeDealerGroup fields = ("advisor", "old_firm", "new_firm", "work_phone", "new_email", "letter_new_group", "letter_previous_group", "signature", "clients") def __init__(self, *args, **kwargs): kwargs.setdefault('label_suffix', '') if "data" in kwargs: q = QueryDict('', mutable=True) q.update(kwargs["data"]) initial = dict() initial["advisor"] = str(kwargs["initial"]["advisor"].pk) initial["old_firm"] = str(kwargs["initial"]["old_firm"].pk) q.update(initial) kwargs["data"] = q super(ChangeDealerGroupForm, self).__init__(*args, **kwargs) self.field_sections = [ { "fields": ('new_firm', 'work_phone', 'new_email'), "header": "New arrangements" }, { "fields": ('clients', ), "header": "Your current investors" }, { "fields": ('letter_previous_group', ), "header": "Previous Dealer Group Release Authorization", "detail": mark_safe( "A letter from your previous Dealer Group authorising the release " "of your current investors. A template of this letter has been supplied, " "This letter must be provided on the previous Dealer Group's " "company letterhead. <a target='_blank' href='{}'>Example</a>" .format( static( 'docs/previous_dealer_group_release_authorization.pdf' ))) }, { "fields": ('letter_new_group', ), "header": "New Dealer Group Acceptance Authorization", "detail": mark_safe( "A letter from the new Dealer Group accepting the transfer of your " "current investors. A template of this letter has been supplied. This letter" "must be provided on the new Dealer Group's company letterhead. " "<a target='_blank' href='{}'>Example</a>".format( static( 'docs/new_dealer_group_acceptance_authorization.pdf' ))) }, { "fields": ('signature', ), "header": "Advisor Signature", "detail": mark_safe( "Please upload a signature approval by an Authorised Signatory of the new Dealer Group. " "<a target='_blank' href='{}'>Example</a>".format( static( 'docs/advisor_signature_change_dealer_group.pdf'))) }, ] self.fields["new_firm"].queryset = Firm.objects.exclude( pk=self.initial["old_firm"].pk) self.fields["clients"].queryset = self.initial["advisor"].clients def clean_new_email(self): email = self.cleaned_data["new_email"] if User.objects.exclude(pk=self.initial["advisor"].user.pk).filter( email=email).count(): self._errors['new_email'] = "User with this email already exists" return email @property def sections(self): for section in self.field_sections: yield Section(section, self)
class EventForm(happyforms.ModelForm): """Form of an event.""" categories = forms.ModelMultipleChoiceField( queryset=FunctionalArea.active_objects.all()) goals = forms.ModelMultipleChoiceField( queryset=EventGoal.active_objects.all()) country = forms.ChoiceField( choices=[], error_messages={'required': 'Please select one option from the list.'}) swag_bug_form = forms.CharField(required=False) budget_bug_form = forms.CharField(required=False) estimated_attendance = forms.IntegerField( validators=[MinValueValidator(1)], error_messages={'invalid': 'Please enter a number.'}) owner = forms.IntegerField(required=False) timezone = forms.ChoiceField(choices=zip(common_timezones, common_timezones)) start = forms.DateTimeField(required=False) end = forms.DateTimeField(required=False) def __init__(self, *args, **kwargs): """Initialize form. Dynamically set choices for country field. """ if 'editable_owner' in kwargs: self.editable_owner = kwargs['editable_owner'] del(kwargs['editable_owner']) self.clone = kwargs.pop('clone', None) super(EventForm, self).__init__(*args, **kwargs) # Dynamic categories/goals field. if self.instance.id: categories_query = (Q(active=True) | Q(id__in=self.instance.categories.all())) goals_query = Q(active=True) | Q(id__in=self.instance.goals.all()) categories = FunctionalArea.objects.filter(categories_query) goals = EventGoal.objects.filter(goals_query) self.fields['categories'].queryset = categories self.fields['goals'].queryset = goals # Dynamic countries field. countries = product_details.get_regions('en').values() countries.sort() country_choices = ([('', "Country")] + [(country, country) for country in countries]) self.fields['country'].choices = country_choices # Dynamic owner field. if self.editable_owner: self.fields['owner_form'] = forms.ModelChoiceField( queryset=User.objects.filter( userprofile__registration_complete=True, groups__name='Rep'), empty_label='Owner', initial=self.instance.owner.pk) else: self.fields['owner_form'] = forms.CharField( required=False, initial=get_full_name(self.instance.owner), widget=forms.TextInput(attrs={'readonly': 'readonly', 'class': 'input-text big'})) instance = self.instance # Dynamically set the year portion of the datetime widget start_year = min(getattr(self.instance.start, 'year', now().year), now().year - 1) end_year = min(getattr(self.instance.end, 'year', now().year), now().year - 1) self.fields['start_form'] = forms.DateTimeField( widget=SplitSelectDateTimeWidget( years=range(start_year, start_year + 10), minute_step=5), validators=[validate_datetime]) self.fields['end_form'] = forms.DateTimeField( widget=SplitSelectDateTimeWidget( years=range(end_year, end_year + 10), minute_step=5), validators=[validate_datetime]) # Make times local to venue if self.instance.start: start = make_naive(instance.local_start, timezone(instance.timezone)) self.fields['start_form'].initial = start if self.instance.end: end = make_naive(instance.local_end, timezone(instance.timezone)) self.fields['end_form'].initial = end # Use of intermediate fields to translate between bug.id and # bug.bug_id if instance.budget_bug: self.fields['budget_bug_form'].initial = instance.budget_bug.bug_id if instance.swag_bug: self.fields['swag_bug_form'].initial = instance.swag_bug.bug_id def clean(self): """Clean form.""" super(EventForm, self).clean() cdata = self.cleaned_data cdata['budget_bug'] = cdata.get('budget_bug_form', None) cdata['swag_bug'] = cdata.get('swag_bug_form', None) if self.editable_owner: cdata['owner'] = cdata.get('owner_form', None) else: cdata['owner'] = self.instance.owner # Check if keys exists in cleaned data. if not all(k in cdata for k in ('start_form', 'end_form')): raise ValidationError('Please correct the form errors.') # Set timezone t = timezone(cdata['timezone']) start = make_naive(cdata['start_form'], timezone(settings.TIME_ZONE)) cdata['start'] = t.localize(start) end = make_naive(cdata['end_form'], timezone(settings.TIME_ZONE)) cdata['end'] = t.localize(end) if cdata['start'] >= cdata['end']: msg = 'Start date should come before end date.' self._errors['start_form'] = self.error_class([msg]) return cdata def _clean_bug(self, bug_id): """Get or create Bug with bug_id and component. """ if bug_id == '': return None try: bug_id = int(bug_id) except ValueError: raise ValidationError('Please provide a number') bug, created = Bug.objects.get_or_create(bug_id=bug_id) return bug def clean_swag_bug_form(self): """Clean swag_bug_form field.""" data = self.cleaned_data['swag_bug_form'] return self._clean_bug(data) def clean_budget_bug_form(self): """Clean budget_bug_form field.""" data = self.cleaned_data['budget_bug_form'] return self._clean_bug(data) def save(self, *args, **kwargs): """Override save method for custom functionality.""" if self.clone: self.instance.pk = None self.instance.slug = None self.instance.has_new_metrics = True self.instance.actual_attendance = None return super(EventForm, self).save() class Meta: model = Event fields = ['name', 'start', 'end', 'venue', 'region', 'owner', 'country', 'city', 'lat', 'lon', 'external_link', 'planning_pad_url', 'timezone', 'estimated_attendance', 'description', 'extra_content', 'hashtag', 'mozilla_event', 'swag_bug', 'budget_bug', 'categories', 'goals'] widgets = {'lat': forms.HiddenInput(attrs={'id': 'lat'}), 'lon': forms.HiddenInput(attrs={'id': 'lon'}), 'start': SplitSelectDateTimeWidget(), 'end': SplitSelectDateTimeWidget()}
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) user_list = Employee.objects.all().order_by('name') self.fields["employee"] = forms.ModelMultipleChoiceField( queryset=user_list, )
def __init__(self, team, *args, **kwargs): super(TeamScheduleForm, self).__init__(*args, **kwargs) self.fields['users'] = forms.ModelMultipleChoiceField( queryset=team.users)
class BaseActionForm(forms.Form): ALLOWED_ACTIONS = (('label', _("Label Messages")), ('archive', _("Archive Messages")), ('inbox', _("Move to Inbox")), ('resend', _("Resend Messages")), ('delete', _("Delete Messages"))) OBJECT_CLASS = Msg LABEL_CLASS = Label LABEL_CLASS_MANAGER = 'all_objects' HAS_IS_ACTIVE = False action = forms.ChoiceField(choices=ALLOWED_ACTIONS) label = forms.ModelChoiceField(getattr(LABEL_CLASS, LABEL_CLASS_MANAGER).all(), required=False) objects = forms.ModelMultipleChoiceField(OBJECT_CLASS.objects.all()) add = forms.BooleanField(required=False) number = forms.BooleanField(required=False) def __init__(self, *args, **kwargs): org = kwargs['org'] self.user = kwargs['user'] del kwargs['org'] del kwargs['user'] super(BaseActionForm, self).__init__(*args, **kwargs) self.fields['action'].choices = self.ALLOWED_ACTIONS self.fields['label'].queryset = getattr( self.LABEL_CLASS, self.LABEL_CLASS_MANAGER).filter(org=org) self.fields['objects'].queryset = self.OBJECT_CLASS.objects.filter( org=org) if self.HAS_IS_ACTIVE: self.fields['objects'].queryset = self.OBJECT_CLASS.objects.filter( org=org, is_active=True) def clean(self): data = self.cleaned_data action = data['action'] update_perm_codename = self.OBJECT_CLASS.__name__.lower() + "_update" update_allowed = self.user.get_org_group().permissions.filter( codename=update_perm_codename) delete_allowed = self.user.get_org_group().permissions.filter( codename="msg_update") resend_allowed = self.user.get_org_group().permissions.filter( codename="broadcast_send") if action in [ 'label', 'unlabel', 'archive', 'restore', 'block', 'unblock' ] and not update_allowed: raise forms.ValidationError( _("Sorry you have no permission for this action.")) if action == 'delete' and not delete_allowed: raise forms.ValidationError( _("Sorry you have no permission for this action.")) if action == 'resend' and not resend_allowed: raise forms.ValidationError( _("Sorry you have no permission for this action.")) if action == 'label' and 'label' not in self.cleaned_data: raise forms.ValidationError(_("Must specify a label")) if action == 'unlabel' and 'label' not in self.cleaned_data: raise forms.ValidationError(_("Must specify a label")) return data def execute(self): data = self.cleaned_data action = data['action'] objects = data['objects'] if action == 'label': label = data['label'] add = data['add'] if not label: return dict(error=_("Missing label")) changed = self.OBJECT_CLASS.apply_action_label(objects, label, add) return dict(changed=changed, added=add, label_id=label.id, label=label.name) elif action == 'unlabel': label = data['label'] add = data['add'] if not label: return dict(error=_("Missing label")) changed = self.OBJECT_CLASS.apply_action_label( objects, label, False) return dict(changed=changed, added=add, label_id=label.id, label=label.name) elif action == 'archive': changed = self.OBJECT_CLASS.apply_action_archive(objects) return dict(changed=changed) elif action == 'block': changed = self.OBJECT_CLASS.apply_action_block(objects) return dict(changed=changed) elif action == 'unblock': changed = self.OBJECT_CLASS.apply_action_unblock(objects) return dict(changed=changed) elif action == 'restore': changed = self.OBJECT_CLASS.apply_action_restore(objects) return dict(changed=changed) elif action == 'delete': changed = self.OBJECT_CLASS.apply_action_delete(objects) return dict(changed=changed) elif action == 'resend': changed = self.OBJECT_CLASS.apply_action_resend(objects) return dict(changed=changed) # should never make it here else: # pragma: no cover return dict(error=_("Oops, so sorry. Something went wrong!")) # no action means no-op return dict() # pragma: no cover
class ProjectForm(forms.Form): name = forms.CharField(max_length=500) requester = forms.ModelChoiceField(People.objects.all()) project_manager = forms.ModelChoiceField( People.objects.filter(group__internal=True)) description = forms.CharField(widget=forms.Textarea(attrs={ 'rows': 10, 'cols': 60 })) start_date = forms.DateField() due_date = forms.DateField(required=False) date_complete = forms.DateField(required=False) sharepoint_ticket = forms.URLField(required=False) priority = forms.ChoiceField(choices=Project.PRIORITY_CHOICES, initial=Project.STANDARD) status = forms.ChoiceField(choices=Project.STATUS_CHOICES) program = forms.ModelChoiceField(Program.objects.all(), empty_label=None, initial="None") workers = forms.ModelMultipleChoiceField(queryset=People.objects.all()) def __init__(self, *args, **kwargs): super(ProjectForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = "create_project" self.helper.form_action = "pm:project-new" self.helper.add_input(Submit('submit', 'Submit')) self.helper.layout = Layout( Div( Div(Field('name'), css_class='col-sm-6'), Div(Field('requester'), css_class='col-sm-3'), Div(Field('project_manager'), css_class='col-sm-3'), css_class='row', ), Div( Div(Field('description'), css_class='col-sm-6'), Div( Div( Div(Field('start_date'), css_class='col-sm-6 datemask'), Div(Field('program'), css_class='col-sm-6'), css_class='row', ), Div( Div(Field('due_date'), css_class='col-sm-6 datemask'), Div(Field('status'), css_class='col-sm-6'), css_class='row', ), Div( Div(Field('date_complete'), css_class='col-sm-6 datemask'), Div(Field('priority'), css_class='col-sm-6'), css_class='row', ), css_class='col-sm-6', ), css_class='row', ), Div( Div(Field('sharepoint_ticket'), css_class='col-sm-6'), Div(Field('workers'), css_class='col-sm-6'), css_class='row', ))
class ContributionForm(forms.ModelForm): responsibility = forms.ChoiceField( widget=forms.RadioSelect(), choices=Contribution.RESPONSIBILITY_CHOICES) course = forms.ModelChoiceField(Course.objects.all(), disabled=True, required=False, widget=forms.HiddenInput()) questionnaires = forms.ModelMultipleChoiceField( Questionnaire.objects.filter(is_for_contributors=True, obsolete=False), required=False, widget=CheckboxSelectMultiple, label=_("Questionnaires")) does_not_contribute = forms.BooleanField( required=False, label=_("Does not contribute to course")) class Meta: model = Contribution fields = ('course', 'contributor', 'questionnaires', 'order', 'responsibility', 'comment_visibility', 'label') widgets = { 'order': forms.HiddenInput(), 'comment_visibility': forms.RadioSelect(choices=Contribution.COMMENT_VISIBILITY_CHOICES) } field_classes = { 'contributor': UserModelChoiceField, } def __init__(self, *args, **kwargs): # work around https://code.djangoproject.com/ticket/25880 self.course = kwargs.pop('course', None) if self.course is None: assert 'instance' in kwargs self.course = kwargs['instance'].course super().__init__(*args, **kwargs) self.fields['contributor'].widget.attrs['class'] = 'form-control' self.fields['label'].widget.attrs['class'] = 'form-control' if self.instance.responsible: self.fields['responsibility'].initial = Contribution.IS_RESPONSIBLE elif self.instance.can_edit: self.fields['responsibility'].initial = Contribution.IS_EDITOR else: self.fields['responsibility'].initial = Contribution.IS_CONTRIBUTOR self.fields['questionnaires'].queryset = Questionnaire.objects.filter( is_for_contributors=True).filter( Q(obsolete=False) | Q(contributions__course=self.course)).distinct() if self.instance.pk: self.fields[ 'does_not_contribute'].initial = not self.instance.questionnaires.exists( ) if not self.course.can_staff_edit: # form is used as read-only course view disable_all_fields(self) def clean(self): if not self.cleaned_data.get( 'does_not_contribute') and not self.cleaned_data.get( 'questionnaires'): self.add_error( 'does_not_contribute', _("Select either this option or at least one questionnaire!")) def save(self, *args, **kwargs): responsibility = self.cleaned_data['responsibility'] is_responsible = responsibility == Contribution.IS_RESPONSIBLE is_editor = responsibility == Contribution.IS_EDITOR self.instance.responsible = is_responsible self.instance.can_edit = is_responsible or is_editor if is_responsible: self.instance.comment_visibility = Contribution.ALL_COMMENTS return super().save(*args, **kwargs)
def get_content_field(self, q, initial): tz = pytz.timezone(self.placeholder.question.event.settings.timezone) label = "" help_text = "" required = False if q.type == Question.TYPE_BOOLEAN: widget = forms.CheckboxInput() initialbool = initial == "True" return forms.BooleanField( label=label, required=False, help_text=help_text, initial=initialbool, widget=widget, ) if q.type == Question.TYPE_NUMBER: return forms.DecimalField( label=label, required=required, help_text=q.help_text, initial=initial, ) if q.type == Question.TYPE_STRING: return forms.CharField( label=label, required=required, help_text=help_text, initial=initial, ) if q.type == Question.TYPE_TEXT: return forms.CharField( label=label, required=required, help_text=help_text, widget=forms.Textarea, initial=initial, ) if q.type == Question.TYPE_COUNTRYCODE: return CountryField( countries=CachedCountries, blank=True, null=True, blank_label=" ", ).formfield( label=label, required=required, help_text=help_text, widget=forms.Select, empty_label=" ", initial=initial, ) if q.type == Question.TYPE_CHOICE: return forms.ModelChoiceField( queryset=q.options, label=label, required=required, help_text=help_text, widget=forms.Select, to_field_name="identifier", empty_label="", initial=q.options.filter( pk=initial).first() if initial else None, ) elif q.type == Question.TYPE_CHOICE_MULTIPLE: return forms.ModelMultipleChoiceField( queryset=q.options, label=label, required=required, help_text=help_text, to_field_name="identifier", widget=QuestionCheckboxSelectMultiple, initial=initial, ) elif q.type == Question.TYPE_DATE: attrs = {} if q.valid_date_min: attrs["data-min"] = q.valid_date_min.isoformat() if q.valid_date_max: attrs["data-max"] = q.valid_date_max.isoformat() field = forms.DateField( label=label, required=required, help_text=help_text, initial=dateutil.parser.parse(initial).date() if initial and initial else None, widget=DatePickerWidget(attrs), ) if q.valid_date_min: field.validators.append(MinDateValidator(q.valid_date_min)) if q.valid_date_max: field.validators.append(MaxDateValidator(q.valid_date_max)) return field elif q.type == Question.TYPE_TIME: return forms.TimeField( label=label, required=required, help_text=help_text, initial=dateutil.parser.parse(initial).time() if initial and initial else None, widget=TimePickerWidget(time_format=get_format_without_seconds( "TIME_INPUT_FORMATS")), ) elif q.type == Question.TYPE_DATETIME: field = SplitDateTimeField( label=label, required=required, help_text=help_text, initial=dateutil.parser.parse(initial).astimezone(tz) if initial else None, widget=SplitDateTimePickerWidget( time_format=get_format_without_seconds( "TIME_INPUT_FORMATS"), min_date=q.valid_datetime_min, max_date=q.valid_datetime_max, ), ) if q.valid_datetime_min: field.validators.append( MinDateTimeValidator(q.valid_datetime_min)) if q.valid_datetime_max: field.validators.append( MaxDateTimeValidator(q.valid_datetime_max)) return field elif q.type == Question.TYPE_PHONENUMBER: return PhoneNumberField( label=label, required=required, help_text=help_text, initial=initial, widget=WrappedPhoneNumberPrefixWidget(), )
class UserFormEdit(forms.ModelForm): ''' Form che Eredita parte del form di registrazione, inserisci tutti i campi del formdeglu utenti, vengono controllati la validità di tutti i form ''' last_login = forms.DateTimeField( label='Ultimo Login', input_formats=('%d-%m-%Y %H:%M:%S', ), widget=forms.DateTimeInput(attrs={'class': 'form-control'}, format='%d-%m-%Y %H:%M:%S'), error_messages={'invalid': 'Inserisci una Data corretta'}, help_text=" formato :'dd-mm-aaaa h:m:s", required=False) date_joined = forms.DateTimeField( label='Data Registrazione', input_formats=('%d-%m-%Y %H:%M:%S', ), widget=forms.DateTimeInput(attrs={'class': 'form-control'}, format='%d-%m-%Y %H:%M:%S'), error_messages={'invalid': 'Inserisci una Data corretta'}, help_text=" formato :'dd-mm-aaaa h:m:s", required=False) #user_permissions = forms.ModelMultipleChoiceField(label='Permessi Utente',queryset=Permission.objects.all(),required=False,widget=forms.SelectMultiple(attrs={'class':'form-control'})) groups = forms.ModelMultipleChoiceField( label='Gruppi', queryset=Group.objects.all(), required=False, widget=forms.SelectMultiple(attrs={'class': 'form-control'})) def clean_username(self): username = self.cleaned_data['username'] username_check = UserProfile.objects.exclude( username=self.instance.username).filter(username__iexact=username) if username_check: raise forms.ValidationError('Utente già presente') return username class Meta(): model = UserProfile fields = '__all__' exclude = ['password', 'username'] labels = { 'email': 'Indirizzo Email*', 'first_name': 'Nome*', 'last_name': 'Cognome*', 'is_superuser': '******', 'password': '******', 'username': '******', 'ripetipassword': '******', 'azienda': 'Azienda*' } help_texts = { 'is_superuser': "******", 'is_staff': "Se selezionato l'utente puo accedere alla pagina Admin", 'is_active': "Se selezionato l'utente è disattivato", } max_length = {'email': 50} widgets = { 'username': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Username' }), 'email': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Email', }), 'note': forms.Textarea(attrs={ 'class': 'form-control', }), 'password': forms.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': 'Password' }), 'first_name': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Nome', }), 'last_name': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Cognome' }), 'azienda': forms.Select(attrs={ 'class': 'form-control', 'placeholder': 'Seleziona Azienda' }), 'telefono': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Numero di Telefono' }), 'user_permissions': forms.SelectMultiple(attrs={ 'class': 'form-control', 'placeholder': 'Permessi Utente' }), } error_messages = { 'username': { 'invalid': "Utente deve contenere valori validi", 'required': "Il campo non può essere vuoto", 'unique': "Utente gia presente" }, 'email': { 'invalid': "L'email inserita non è valida!", 'required': 'Il campo non può essere vuoto' }, 'first_name': { 'required': "Il campo non può essere vuoto", }, 'last_name': { 'required': "Il campo non può essere vuoto" } }
class Metadata12Form(Metadata10Form): supported_platform = forms.CharField(required=False, widget=forms.Textarea(), help_text=_( u'The OS and CPU for which ' 'the binary package was ' 'compiled.')) keywords = forms.CharField(required=False, help_text=_( u'A list of additional keywords to ' 'be used to assist searching for the ' 'package in a larger catalog')) download_url = forms.URLField(required=False, verify_exists=True, help_text=_( u'A string containing the URL for ' 'the package\'s home page.')) author_email = forms.CharField(required=False, help_text=_( u'A string containing the ' 'author\'s e-mail address. It ' 'can contain a name and e-mail ' 'address in the legal forms for ' 'a RFC-822 \'From:\' header.')) maintainer = forms.CharField(required=False, widget=forms.Textarea(), help_text=_( u'A string containing at a minimum ' 'the maintainer\'s name. Contact ' 'information can also be added, ' 'separating each line with ' 'newlines.')) maintainer_email = forms.CharField(required=False, help_text=_( u'A string containing the ' 'maintainer\'s e-mail address. ' 'It can contain a name and ' 'e-mail address in the legal ' 'forms for a RFC-822 ' '\'From:\' header.')) license = forms.CharField(required=False, widget=forms.Textarea(), help_text=_( u'Text indicating the license ' 'covering the package where the ' 'license is not a selection from the ' '"License" Trove classifiers.')) classifier = forms.ModelMultipleChoiceField( required=False, queryset=Classifier.objects.all(), help_text=_(u'Trove classifiers')) requires_dist = LinesField(required=False, help_text=_( u'Each line contains a string ' 'describing some other module or ' 'package required by this package.')) provides_dist = LinesField(required=False, help_text=_( u'Each line contains a string ' 'describing a package or module that ' 'will be provided by this package ' 'once it is installed')) obsoletes_dist = LinesField(required=False, help_text=_( u'Each line contains a string ' 'describing a package or module that ' 'this package renders obsolete, ' 'meaning that the two packages ' 'should not be installed at the ' 'same time')) requires_python = forms.CharField(required=False, help_text=_(u'This field specifies the ' 'Python version(s) that the ' 'distribution is guaranteed ' 'to be compatible with.')) requires_external = forms.CharField(required=False, widget=forms.Textarea(), help_text=_(u'Each line contains a ' 'string describing some ' 'dependency in the system ' 'that the distribution is ' 'to be used.')) project_url = forms.CharField(required=False, widget=forms.Textarea(), help_text=_( u'Each line is a string containing ' 'a browsable URL for the project ' 'and a label for it, separated ' 'by a comma: "Bug Tracker, ' 'http://bugs.project.com"'))
class OrgExtForm(OrgForm): """Also configure available languages for this organization. The motivation is that given a many-org (i.e., country) installation, the global list of languages could get very long. Each org is probably interested in seeing only a subset of those languages. """ available_languages = forms.MultipleChoiceField( choices=settings.LANGUAGES, help_text=_( "The languages used by administrators in your organization")) show_spoof_data = forms.BooleanField( required=False, help_text=_("Whether to show spoof data for this organization.")) contact_fields = forms.ModelMultipleChoiceField( queryset=None, required=False, help_text=_("Custom contact data fields that should be visible " "and editable in TracPro.")) def __init__(self, *args, **kwargs): super(OrgExtForm, self).__init__(*args, **kwargs) # Modify the language field to better match our usage. language = self.fields['language'] language.required = True language.label = _("Default language") language.help_text = _("The default language for your organization") # All orgs must use a subdomain. self.fields['subdomain'].required = True # Config field values are not set automatically. self.fields['available_languages'].initial = self.instance.available_languages or [] self.fields[ 'show_spoof_data'].initial = self.instance.show_spoof_data or False if not self.instance.pk: # We don't have this org's API key yet, # so we can't get available fields from the RapidPro API. self.fields.pop('contact_fields') else: try: # Make sure we have the most up-to-date DataField info. # NOTE: This makes an in-band request to an external API. DataField.objects.sync(self.instance) except TembaAPIError as e: if utils.caused_by_bad_api_key(e): # Org has an invalid API key, but user needs to be # able to access this form in order to update it. pass else: raise data_fields = self.instance.datafield_set.all() self.fields['contact_fields'].queryset = data_fields self.fields['contact_fields'].initial = data_fields.visible() def clean(self): """Ensure the default language is chosen from the available languages.""" language = self.cleaned_data.get('language') available_languages = self.cleaned_data.get( 'available_languages') or [] if language and available_languages: # otherwise, default errors are preferred if language not in available_languages: raise forms.ValidationError( _("Default language must be one of the languages available " "for this organization.")) return self.cleaned_data def save(self, *args, **kwargs): # Config field values are not set automatically. if 'available_languages' in self.fields: available_languages = self.cleaned_data.get('available_languages') self.instance.available_languages = available_languages or [] if 'show_spoof_data' in self.fields: show_spoof_data = self.cleaned_data.get('show_spoof_data') self.instance.show_spoof_data = show_spoof_data or False if 'contact_fields' in self.fields: # Set hook that will be picked up by a post-save signal. # Must be done post-save to avoid making changes if any earlier # part of the transaction fails. self.instance._visible_data_fields = self.cleaned_data.get( 'contact_fields') return super(OrgExtForm, self).save(*args, **kwargs)
class GroupActionForm(forms.Form): orgs = forms.ModelMultipleChoiceField(queryset=Organization.objects.all(), widget=ModelMultiRawInput) action = forms.ChoiceField(choices=[('hide_recommendations', ''), ('unhide_recommendations', '')])