我们从Python开源项目中,提取了以下37个代码示例,用于说明如何使用django.forms.ModelMultipleChoiceField()。
def preferences(request): class NotificationPreferenceForm(forms.ModelForm): event = forms.ChoiceField(choices=registry.get_event_choices(), disabled=True, widget=forms.HiddenInput()) method = forms.ChoiceField(choices=registry.get_method_choices(), disabled=True, widget=forms.HiddenInput()) business_lines = forms.ModelMultipleChoiceField(BusinessLine.authorization.for_user(request.user, 'incidents.view_incidents'), required=False) class Meta: fields = "__all__" formset = forms.inlineformset_factory(User, NotificationPreference, formset=NotificationPreferenceFormset, form=NotificationPreferenceForm) if request.method == 'POST': fs = formset(request.POST, instance=request.user) if fs.is_valid(): fs.save() return redirect('user:profile') else: fs = formset(instance=request.user) return render(request, "fir_async/preferences.html", {'formset': fs})
def __init__(self, user=None, *args, **kwargs): super(FamilyAnalysisForm, self).__init__(*args, **kwargs) if not user.is_authenticated(): # print('user None', user) self.fields['mother'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=None).order_by('id'), required=False) self.fields['father'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=None).order_by('id'), required=False) self.fields['children'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=None).order_by('id'), required=False) self.fields['exclude_individuals'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=None).order_by('id'), required=False) else: # print('user', user) self.fields['mother'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=user).order_by('id'), required=False) self.fields['father'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=user).order_by('id'), required=False) self.fields['children'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=user).order_by('id'), required=False) self.fields['exclude_individuals'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=user).order_by('id'), required=False) # INDIVIDUALS = [(x.id, x.name) for x in Individual.objects.all().order_by('id')]
def _save_to_answer(self, field, answer, value): action = 'pretalx.submission.answer' + ('update' if answer.pk else 'create') if isinstance(field, forms.ModelMultipleChoiceField): answstr = ', '.join([str(o) for o in value]) if not answer.pk: answer.save() else: answer.options.clear() answer.answer = answstr answer.options.add(*value) elif isinstance(field, forms.ModelChoiceField): if not answer.pk: answer.save() else: answer.options.clear() answer.options.add(value) answer.answer = value.answer elif isinstance(field, forms.FileField): if isinstance(value, UploadedFile): answer.answer_file.save(value.name, value) answer.answer = 'file://' + value.name value = answer.answer else: answer.answer = value answer.log_action(action, person=self.request_user, data={'answer': value})
def save(self, *args, **kwargs): instance = super(SettingsModelForm, self).save(*args, **kwargs) if self.__editing_instance: # Django < 1.5 returns list objects when ModelMultipleChoiceField # is empty.. so check before calling delete() if self.cleaned_data['delete_subscriptions']: self.cleaned_data['delete_subscriptions'].delete() if self.cleaned_data['email'] == 1: instance.subscription_set.all().update( send_emails=False, ) if self.cleaned_data['email'] == 2: instance.subscription_set.all().update( send_emails=True, ) return instance
def ChildForm(instance): """ Form for editing a Child model. This is roughly based on the equivalent ModelForm, but uses Form as a base class so that selection boxes for the AS and Prefixes can be edited in a single form. """ class _wrapped(forms.Form): valid_until = forms.DateTimeField(initial=instance.valid_until) as_ranges = forms.ModelMultipleChoiceField(queryset=models.ChildASN.objects.filter(child=instance), required=False, label='AS Ranges', help_text='deselect to remove delegation') address_ranges = forms.ModelMultipleChoiceField(queryset=models.ChildNet.objects.filter(child=instance), required=False, help_text='deselect to remove delegation') return _wrapped
def __init__(self, *args, poll, **kwargs): super().__init__(*args, **kwargs) self.poll = poll self.helper = FormHelper() if 'options' in self.poll.rules and self.poll.rules['options'] == 1: self.fields['choice'] = ModelChoiceField( label='Choix', queryset=poll.options.all().order_by('?'), widget=RadioSelect, required=True, empty_label=None, initial=None, ) else: self.fields['choice'] = ModelMultipleChoiceField( label='Choix', queryset=poll.options.all().order_by('?'), widget=CheckboxSelectMultiple(), ) self.helper.add_input(Submit('submit', 'Confirmer'))
def get_form(self): """ Provide a standard bulk delete form if none has been specified for the view """ class BulkDeleteForm(ConfirmationForm): pk = ModelMultipleChoiceField(queryset=self.cls.objects.all(), widget=MultipleHiddenInput) if self.form: return self.form return BulkDeleteForm # # Device/VirtualMachine components #
def __init__(self, *args, **kwargs): self.helper = kwargs.pop('helper') self.user = kwargs.pop('user') super(HelperAddShiftForm, self).__init__(*args, **kwargs) event = self.helper.event # field that contains all shifts if # - user is admin for shift/job # - helper is not already in this shift # all administered shifts administered_jobs = [job for job in event.job_set.all() if job.is_admin(self.user)] shifts = Shift.objects.filter(job__event=event, job__in=administered_jobs) # exclude already taken shifts shifts = shifts.exclude(id__in=self.helper.shifts.all()) # add field self.fields['shifts'] = forms.ModelMultipleChoiceField( widget=forms.CheckboxSelectMultiple, queryset=shifts, required=True)
def __init__(self, *args, **kwargs): self.helper = kwargs.pop('helper') self.user = kwargs.pop('user') super(HelperAddCoordinatorForm, self).__init__(*args, **kwargs) event = self.helper.event # field that contains all jobs if # - user is admin for job # - helper is not already coordinator for this job # all administered jobs coordinated_jobs = self.helper.coordinated_jobs jobs = [job.pk for job in event.job_set.all() if job.is_admin(self.user) and job not in coordinated_jobs] # we need a queryset jobs = Job.objects.filter(pk__in=jobs) # add field self.fields['jobs'] = forms.ModelMultipleChoiceField( widget=forms.CheckboxSelectMultiple, queryset=jobs, required=True)
def __init__(self, user=None, *args, **kwargs): super(ComparisonForm, self).__init__(*args, **kwargs) if not user.is_authenticated(): print('user None', user) self.fields['individual_one'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=None).order_by('id'), required=False) self.fields['individual_two'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=None).order_by('id'), required=False) else: print('user', user) self.fields['individual_one'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=user).order_by('id'), required=False) self.fields['individual_two'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=user).order_by('id'), required=False)
def __init__(self, user=None, *args, **kwargs): super(FilterAnalysisForm, self).__init__(*args, **kwargs) if not user.is_authenticated(): # print('user None', user) self.fields['individuals'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=None).order_by('id'), required=False, label='INDIVIDUALS') self.fields['exclude_individuals'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=None).order_by('id'), required=False, label='INDIVIDUALS') else: print('user', user) if user.is_superuser: self.fields['individuals'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter().order_by('id'), required=False, label='INDIVIDUALS') self.fields['exclude_individuals'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter().order_by('id'), required=False, label='INDIVIDUALS') else: self.fields['individuals'] = forms.ModelMultipleChoiceField( queryset=Individual.objects.filter(Q(user=user) | Q(user=None)).order_by('id'), required=False, label='INDIVIDUALS') self.fields['exclude_individuals'] = forms.ModelMultipleChoiceField( queryset=Individual.objects.filter(Q(user=user) | Q(user=None)).order_by('id'), required=False, label='INDIVIDUALS') # self.fields['sift'].widget.attrs['readonly'] = True # self.fields['polyphen'].widget.attrs['readonly'] = True # self.fields['genomes1000'].widget.attrs['readonly'] = True # self.fields['dbsnp_frequency'].widget.attrs['readonly'] = True # self.fields['esp_frequency'].widget.attrs['readonly'] = True #trio analysis
def formfield(self, **kwargs): db = kwargs.pop('using', None) defaults = { 'form_class': forms.ModelMultipleChoiceField, 'queryset': self.remote_field.model._default_manager.using(db), } defaults.update(kwargs) # If initial is passed in, it's a list of related objects, but the # MultipleChoiceField takes a list of IDs. if defaults.get('initial') is not None: initial = defaults['initial'] if callable(initial): initial = initial() defaults['initial'] = [i._get_pk_val() for i in initial] return super(ManyToManyField, self).formfield(**defaults)
def __init__(self, *args: Any, **kwargs: Any) -> None: # self.archive = kwargs.pop("archive") super(ArchiveModForm, self).__init__(*args, **kwargs) self.fields["possible_matches"].queryset = self.instance.possible_matches.order_by( "-archivematches__match_accuracy") # custom_tags = forms.ModelMultipleChoiceField(required=False, # queryset=CustomTag.objects.all(), # widget=autocomplete_light.MultipleChoiceWidget('CustomTagAutocomplete'))
def angular_input_field(form_field, angular_model_name, extra_params={}): try: form_field_value = form_field.value form_field.value = lambda: None attrs = {"ng-model": "%s.fields.%s" % (angular_model_name, form_field.name), "class": "form-control"} if form_field.field.required: attrs["required"] = "true" if isinstance(form_field.field, DateTimeField): separator = extra_params.pop("silica_datetime_separator", "") widget1 = _get_datepicker(form_field, attrs, extra_params) attrs["type"] = "time" attrs.update(extra_params) widget2 = form_field.as_widget(attrs=attrs) return format_html(widget1 + separator + widget2) if isinstance(form_field.field, DateField): return format_html(_get_datepicker(form_field, attrs, extra_params)) if isinstance(form_field.field, ModelChoiceField): pass #return format_html(_get_datepicker(form_field, attrs, extra_params)) if isinstance(form_field.field, ModelMultipleChoiceField): pass #return format_html(_get_datepicker(form_field, attrs, extra_params)) attrs.update(extra_params) return format_html(form_field.as_widget(attrs=attrs)) finally: form_field.value = form_field_value
def __init__(self, world, sector, *args, **kwargs): super(attackform, self).__init__(*args, **kwargs) query = world.controlled_fleets.all().exclude(sector='hangar').exclude(sector='warping') query = query.filter(sector=sector) exclude_list = [] for f in query: if f.power() == 0 or f.powermodifiers() == 0: exclude_list.append(f.pk) for pk in exclude_list: query = query.exclude(pk=pk) self.fields['fleets'] = forms.ModelMultipleChoiceField(queryset=query, widget=forms.SelectMultiple( attrs={'style': 'color: black; background-color: white; min-width: 80px;'}))
def __init__(self, *args, **kwargs): bug_queryset = kwargs.pop('queryset') self.bug_actions = kwargs.pop('bug_actions') super().__init__(*args, **kwargs) self.fields['bugs'] = forms.ModelMultipleChoiceField( queryset=bug_queryset, required=True )
def get_form_field(self, **kwargs): from django import forms defaults = {'form_class': forms.ModelMultipleChoiceField, 'queryset': self.reference_class.all(), 'required': False} defaults.update(kwargs) return super(KeyListProperty, self).get_form_field(**defaults)
def add_fields(self, form, index): super(EventOccurrenceCustomFormSet,self).add_fields(form,index) form.fields['startTime'] = forms.SplitDateTimeField(label=_("Start Time"),input_time_formats=['%I:%M%p','%-I:%M%p'], widget=widgets.SplitDateTimeWidget) form.fields['endTime'] = forms.SplitDateTimeField(label=_("End Time"),input_time_formats=['%I:%M%p','%-I:%M%p'], widget=widgets.SplitDateTimeWidget) form.fields['extraOccurrencesToAdd'] = forms.IntegerField(label=_("Repeat __ times:"),initial=0,min_value=0,max_value=100,required=False) form.fields['extraOccurrenceRule'] = forms.ChoiceField(label=_("Every:"),choices=EVENT_REPEAT_CHOICES,required=False) form.fields['sendReminderTo'] = forms.ChoiceField(label=_("Send A Reminder To:"),choices=REMINDER_SET_CHOICES,initial='none',required=False) form.fields['sendReminderWhen'] = forms.ChoiceField(label=_("Before:"),choices=REMINDER_TIME_CHOICES,initial=0,required=False) form.fields['sendReminderWhich'] = forms.ChoiceField(label=_("Ahead Of:"),choices=(('all',_('All Occurrences')),('first',_('First Occurrence Only'))),initial='all',required=False) form.fields['sendReminderGroup'] = forms.ModelChoiceField(label=_("Remind Group:"),queryset=Group.objects.all(),required=False) form.fields['sendReminderUsers'] = forms.ModelMultipleChoiceField(label=_("Remind Users:"),queryset=User.objects.filter(staffmember__isnull=False),required=False)
def formfield(self, **kwargs): return ModelMultipleChoiceField(queryset=TopicLink.objects.all(), to_field_name="target_id", required=False, **kwargs)
def formfield(self, **kwargs): return ModelMultipleChoiceField(queryset=Topic.objects.all(), to_field_name="article_id", required=False, **kwargs)
def formfield(self, **kwargs): return ModelMultipleChoiceField(queryset=Topic.objects.all(), to_field_name="article_id", required=False, **kwargs) #diggly application models
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
def __init__(self , *args , **kwargs): super(Forms_Idc , self).__init__(*args, **kwargs) self.fields['description'].required = False self.fields['provider'].required = False self.fields['tel'].validators = [telno_validate] self.fields['provider'].choices = list_addempty(provider_idcserver_queryset) # provider = forms.ModelMultipleChoiceField(queryset=provider.objects.values('name').distinct())
def __init__(self, name, model_form_class, model_form_kw, *args, **kwargs): form_fields = [] mdl_form_field_names = [] widgets = [] model_form_kwargs = model_form_kw.copy() try: model_form_kwargs['prefix'] = model_form_kwargs['prefix'] + '-' + name except KeyError: model_form_kwargs['prefix'] = name initial = kwargs.pop('initial', None) if initial: model_form_kwargs['initial'] = initial self.model_form_class = model_form_class self.model_form_kwargs = model_form_kwargs error_messages = { 'incomplete': 'Enter all required fields.', } self.model_form = model_form_class(**model_form_kwargs) for field_name, field in self.model_form.fields.items(): if isinstance(field, (forms.ModelChoiceField, forms.ModelMultipleChoiceField)): continue form_fields.append(field) mdl_form_field_names.append(field_name) widgets.append(field.widget) widget = EmbeddedFormWidget(mdl_form_field_names, widgets) super().__init__(error_messages=error_messages, fields=form_fields, widget=widget, require_all_fields=False, *args, **kwargs)
def _create_ssh_keys_field(data, kwargs, user): HT = _(u"<span class='text-warning'>WARNING: if any key is selected, telnet access will be disabled. If unsure leave all boxes unchecked.</span>") kwds = {} instance = kwargs.get('instance', None) if instance: network = instance.network elif data: network = data.get("network") else: network = kwargs.get("initial").get("network") if "initial" in kwargs else None if network and not hasattr(network, "pk"): network = Network.objects.get(id=int(network)) if network: kwds["user__in"] = network.users else: kwds["user"] = user ssh_keys = SSHKey.objects.filter(**kwds) initial = [] if not instance: # select auto_add keys only if the current user has an auto_add key # to avoid creating firmwares where the owner cannot SSH in user_auto_add_key = ssh_keys.filter(user=user, auto_add=True) if user_auto_add_key: initial = [s.pk for s in ssh_keys.filter(auto_add=True)] return forms.ModelMultipleChoiceField( queryset=ssh_keys, widget=forms.CheckboxSelectMultiple, help_text=HT, required=False, initial=initial)
def formfield(self, **kwargs): db = kwargs.pop('using', None) defaults = { 'form_class': forms.ModelMultipleChoiceField, 'queryset': self.rel.to._default_manager.using(db), } defaults.update(kwargs) # If initial is passed in, it's a list of related objects, but the # MultipleChoiceField takes a list of IDs. if defaults.get('initial') is not None: initial = defaults['initial'] if callable(initial): initial = initial() defaults['initial'] = [i._get_pk_val() for i in initial] return super(ManyToManyField, self).formfield(**defaults)
def get_field(self, *, question, initial, initial_object, readonly): if question.variant == QuestionVariant.BOOLEAN: # For some reason, django-bootstrap4 does not set the required attribute # itself. widget = forms.CheckboxInput(attrs={'required': 'required'}) if question.required else forms.CheckboxInput() initialbool = (initial == 'True') if initial else bool(question.default_answer) return forms.BooleanField( disabled=readonly, help_text=question.help_text, label=question.question, required=question.required, widget=widget, initial=initialbool ) elif question.variant == QuestionVariant.NUMBER: return forms.DecimalField( disabled=readonly, help_text=question.help_text, label=question.question, required=question.required, min_value=Decimal('0.00'), initial=initial ) elif question.variant == QuestionVariant.STRING: return forms.CharField( disabled=readonly, help_text=question.help_text, label=question.question, required=question.required, initial=initial ) elif question.variant == QuestionVariant.TEXT: return forms.CharField( label=question.question, required=question.required, widget=forms.Textarea, disabled=readonly, help_text=question.help_text, initial=initial ) elif question.variant == QuestionVariant.FILE: return forms.FileField( label=question.question, required=question.required, disabled=readonly, help_text=question.help_text, initial=initial ) elif question.variant == QuestionVariant.CHOICES: return forms.ModelChoiceField( queryset=question.options.all(), label=question.question, required=question.required, initial=initial_object.options.first() if initial_object else question.default_answer, disabled=readonly, help_text=question.help_text, ) elif question.variant == QuestionVariant.MULTIPLE: return forms.ModelMultipleChoiceField( queryset=question.options.all(), label=question.question, required=question.required, widget=forms.CheckboxSelectMultiple, initial=initial_object.options.all() if initial_object else question.default_answer, disabled=readonly, help_text=question.help_text, )