django.forms.ModelChoiceField - python examples

Here are the examples of the python api django.forms.ModelChoiceField taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

23 Examples 7

3 View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : c3nav
    def __init__(self, *args, request=None, allow_clicked_position=False, **kwargs):
        self.request = request
        super().__init__(*args, **kwargs)

        GraphNode = self.request.changeset.wrap_model('GraphNode')
        graph_node_qs = GraphNode.objects.all()
        self.fields['active_node'] = ModelChoiceField(graph_node_qs, widget=HiddenInput(), required=False)
        self.fields['clicked_node'] = ModelChoiceField(graph_node_qs, widget=HiddenInput(), required=False)

        if allow_clicked_position:
            self.fields['clicked_position'] = CharField(widget=HiddenInput(), required=False)

        Space = self.request.changeset.wrap_model('Space')
        space_qs = Space.objects.all()
        self.fields['goto_space'] = ModelChoiceField(space_qs, widget=HiddenInput(), required=False)

3 View Complete Implementation : forms.py
Copyright MIT License
Author : ic-labs
    def __init__(self, *args, **kwargs):
        """
        Set the default fields and queryset.
        """
        # Parse keyword arguments and past through to each field appropriately.
        queryset = kwargs.pop('queryset', models.RecurrenceRule.objects.all())
        max_length = kwargs.pop('max_length', None)
        validators_ = kwargs.pop('validators', [validators.recurrence_rule])
        fields = (
            forms.ModelChoiceField(queryset=queryset, required=False),
            forms.CharField(required=False),
            forms.CharField(max_length=max_length, validators=validators_),
        )
        kwargs.setdefault('fields', fields)
        kwargs.setdefault('require_all_fields', False)
        super(RecurrenceRuleField, self).__init__(*args, **kwargs)
        self.queryset = queryset

3 View Complete Implementation : forms.py
Copyright MIT License
Author : JamesRamm
    def __init__(self, *args, **kwargs):
        site = kwargs.pop('site', None)
        super(AddressForm, self).__init__(*args, **kwargs)

        # Edit the country field to only contain
        # countries specified for shipping
        all_countries = True
        if site:
            settings = Configuration.for_site(site)
            all_countries = settings.default_shipping_enabled
        if all_countries:
            queryset = Country.objects.all()
        else:
            queryset = Country.objects.exclude(shippingrate=None)
        self.fields['country'] = ModelChoiceField(queryset)

3 View Complete Implementation : blocks.py
Copyright GNU Affero General Public License v3.0
Author : liqd
    @cached_property
    def field(self):
        return forms.ModelChoiceField(
            queryset=self.target_model.objects.filter(
                is_draft=False,
                is_archived=False,
                is_public=True),
            widget=self.widget,
            required=self._required,
            help_text=self._help_text)

3 View Complete Implementation : vlan.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def _set_up_relay_vlan(self):
        # Configure the relay_vlan fields to include only VLAN's that are
        # not already on a relay_vlan. If this is an update then it cannot
        # be itself or never set when dhcp_on is True.
        possible_relay_vlans = VLAN.objects.filter(relay_vlan__isnull=True)
        if self.instance is not None:
            possible_relay_vlans = possible_relay_vlans.exclude(
                id=self.instance.id
            )
            if self.instance.dhcp_on:
                possible_relay_vlans = VLAN.objects.none()
                if self.instance.relay_vlan is not None:
                    possible_relay_vlans = VLAN.objects.filter(
                        id=self.instance.relay_vlan.id
                    )
        self.fields["relay_vlan"] = forms.ModelChoiceField(
            queryset=possible_relay_vlans, required=False
        )

3 View Complete Implementation : test_modelchoicefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_choices_freshness(self):
        f = forms.ModelChoiceField(Category.objects.all())
        self.astertEqual(len(f.choices), 4)
        self.astertEqual(list(f.choices), [
            ('', '---------'),
            (self.c1.pk, 'Entertainment'),
            (self.c2.pk, 'A test'),
            (self.c3.pk, 'Third'),
        ])
        c4 = Category.objects.create(name='Fourth', slug='4th', url='4th')
        self.astertEqual(len(f.choices), 5)
        self.astertEqual(list(f.choices), [
            ('', '---------'),
            (self.c1.pk, 'Entertainment'),
            (self.c2.pk, 'A test'),
            (self.c3.pk, 'Third'),
            (c4.pk, 'Fourth'),
        ])

3 View Complete Implementation : test_modelchoicefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_overridable_choice_iterator(self):
        """
        Iterator defaults to ModelChoiceIterator and can be overridden with
        the iterator attribute on a ModelChoiceField subclast.
        """
        field = forms.ModelChoiceField(Category.objects.all())
        self.astertIsInstance(field.choices, ModelChoiceIterator)

        clast CustomModelChoiceIterator(ModelChoiceIterator):
            past

        clast CustomModelChoiceField(forms.ModelChoiceField):
            iterator = CustomModelChoiceIterator

        field = CustomModelChoiceField(Category.objects.all())
        self.astertIsInstance(field.choices, CustomModelChoiceIterator)

3 View Complete Implementation : test_modelchoicefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_queryset_manager(self):
        f = forms.ModelChoiceField(Category.objects)
        self.astertEqual(len(f.choices), 4)
        self.astertEqual(list(f.choices), [
            ('', '---------'),
            (self.c1.pk, 'Entertainment'),
            (self.c2.pk, 'A test'),
            (self.c3.pk, 'Third'),
        ])

3 View Complete Implementation : test_wiki_templatetags.py
Copyright MIT License
Author : python-discord
    def test_field_model_choice(self):
        field = ModelChoiceField(Article.objects.all())

        context = Context({"field": field})
        self.TEMPLATE.render(context)

        template_path = "wiki/forms/fields/model_choice.html"
        context = {"field": field, "is_markitup": False, "render_labels": True}

        wiki_extra.render.astert_called_with(template_path, context)

0 View Complete Implementation : converter.py
Copyright MIT License
Author : graphql-python
@convert_form_field.register(forms.ModelChoiceField)
@convert_form_field.register(GlobalIDFormField)
def convert_form_field_to_id(field):
    return ID(required=field.required)

0 View Complete Implementation : test_converter.py
Copyright MIT License
Author : graphql-python
def test_should_manytoone_convert_connectionorlist():
    field = forms.ModelChoiceField(queryset=None)
    graphene_type = convert_form_field(field)
    astert isinstance(graphene_type, ID)

0 View Complete Implementation : defaults.py
Copyright GNU Affero General Public License v3.0
Author : helfertool
    def __init__(self, *args, **kwargs):
        self.event = kwargs.pop('event')

        super(BadgeJobDefaultsForm, self).__init__(*args, **kwargs)

        # available roles and designs
        roles = BadgeRole.objects.filter(
            badge_settings=self.event.badge_settings.pk)
        designs = BadgeDesign.objects.filter(
            badge_settings=self.event.badge_settings.pk)

        # add fields for each job
        for job in self.event.job_set.all():
            self.fields['job_%d_design' % job.pk] = forms.ModelChoiceField(
                queryset=designs, required=False,
                initial=job.badge_defaults.design)
            self.fields['job_%d_role' % job.pk] = forms.ModelChoiceField(
                queryset=roles, required=False,
                initial=job.badge_defaults.role)
            self.fields['job_%d_no_def_role' % job.pk] = forms.BooleanField(
                initial=job.badge_defaults.no_default_role,
                required=False,
                label=_("No default role"))

        if self.event.archived:
            for field_id in self.fields:
                self.fields[field_id].disabled = True

0 View Complete Implementation : page_form.py
Copyright Apache License 2.0
Author : Integreat
    def __init__(self, *args, **kwargs):

        logger.info(
            'New PageForm instantiated with args %s and kwargs %s',
            args,
            kwargs
        )

        # pop kwarg to make sure the super clast does not get this param
        self.region = kwargs.pop('region', None)
        language = kwargs.pop('language', None)
        disabled = kwargs.pop('disabled', None)

        # add initial kwarg to make sure changed_data is preserved
        kwargs['initial'] = {
            'position': position.FIRST_CHILD
        }

        # instantiate ModelForm
        super(PageForm, self).__init__(*args, **kwargs)

        # If form is disabled because the user has no permissions to edit the page, disable all form fields
        if disabled:
            for _, field in self.fields.items():
                field.disabled = True

        if len(args) == 1:
            # dirty hack to remove fields when submitted by POST
            del self.fields['editors']
            del self.fields['publishers']
        else:
            # update the querysets otherwise
            self.fields['editors'].queryset = self.get_editor_queryset()
            self.fields['publishers'].queryset = self.get_publisher_queryset()

        # limit possible parents to pages of current region
        parent_queryset = Page.objects.filter(
            region=self.region,
        )

        # check if instance of this form already exists
        if self.instance.id:
            # remove children from possible parents
            children = self.instance.get_descendants(include_self=True)
            parent_queryset = parent_queryset.exclude(id__in=children)
            self.fields['parent'].initial = self.instance.parent

        self.mirrored_page = forms.ModelChoiceField(queryset=Page.objects.all(), required=False)

        if self.instance.mirrored_page:
            self.fields['mirrored_page'].queryset = Page.objects.filter(region=self.instance.mirrored_page.region)
            self.fields['mirrored_page'].initial = self.instance.mirrored_page
            self.fields['mirrored_page_first'].initial = self.instance.mirrored_page_first
            self.fields['mirrored_page_region'].initial = self.instance.mirrored_page.region

        # add the language to the parent field to make sure the translated page satles are shown
        self.fields['parent'].language = language
        self.fields['parent'].queryset = parent_queryset

0 View Complete Implementation : pods.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop("request", None)
        if self.request is None:
            raise ValueError("'request' kwargs is required.")
        self.pod = kwargs.pop("pod", None)
        if self.pod is None:
            raise ValueError("'pod' kwargs is required.")
        super(ComposeMachineForm, self).__init__(*args, **kwargs)

        # Build the fields based on the pod and current pod hints.
        self.fields["cores"] = IntegerField(
            min_value=1, max_value=self.pod.hints.cores, required=False
        )
        self.initial["cores"] = 1
        self.fields["memory"] = IntegerField(
            min_value=1024, max_value=self.pod.hints.memory, required=False
        )
        self.initial["memory"] = 1024
        self.fields["architecture"] = ChoiceField(
            choices=[(arch, arch) for arch in self.pod.architectures],
            required=False,
        )
        self.initial["architecture"] = self.pod.architectures[0]
        if self.pod.hints.cpu_speed > 0:
            self.fields["cpu_speed"] = IntegerField(
                min_value=300,
                max_value=self.pod.hints.cpu_speed,
                required=False,
            )
        else:
            self.fields["cpu_speed"] = IntegerField(
                min_value=300, required=False
            )

        def duplicated_hostname(hostname):
            if Node.objects.filter(hostname=hostname).exists():
                raise ValidationError(
                    'Node with hostname "%s" already exists' % hostname
                )

        self.fields["hostname"] = CharField(
            required=False, validators=[duplicated_hostname, validate_hostname]
        )
        self.initial["hostname"] = make_unique_hostname()
        self.fields["domain"] = ModelChoiceField(
            required=False, queryset=Domain.objects.all()
        )
        self.initial["domain"] = Domain.objects.get_default_domain()
        self.fields["zone"] = ModelChoiceField(
            required=False, queryset=Zone.objects.all()
        )
        self.initial["zone"] = Zone.objects.get_default_zone()
        self.fields["pool"] = ModelChoiceField(
            required=False, queryset=ResourcePool.objects.all()
        )
        self.initial["pool"] = self.pod.pool
        self.fields["storage"] = CharField(
            validators=[storage_validator], required=False
        )
        self.initial["storage"] = "root:8(local)"
        self.fields["interfaces"] = LabeledConstraintMapField(
            validators=[interfaces_validator],
            label="Interface constraints",
            required=False,
        )
        self.initial["interfaces"] = None
        self.fields["skip_commissioning"] = BooleanField(required=False)
        self.initial["skip_commissioning"] = False
        self.allocated_ips = {}

0 View Complete Implementation : fields.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def __init__(self, name, model_form_clast, model_form_kw, model_container,
                 admin=None, request=None, *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_clast = _get_model_form_clast(
            model_form_clast, model_container, admin, request)
        self.model_form_kwargs = model_form_kwargs
        self.admin = admin
        self.request = request

        error_messages = {
            'incomplete': 'Enter all required fields.',
        }

        self.model_form = self.model_form_clast(**model_form_kwargs)
        for field_name, field in self.model_form.fields.items():
            if isinstance(field, (forms.ModelChoiceField, forms.ModelMultipleChoiceField)):
                continue
            elif isinstance(field, ArrayFormField):
                field.name = '%s-%s' % (self.model_form.prefix, field_name)
            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)

0 View Complete Implementation : test_error_messages.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_modelchoicefield(self):
        # Create choices for the model choice field tests below.
        ChoiceModel.objects.create(pk=1, name='a')
        ChoiceModel.objects.create(pk=2, name='b')
        ChoiceModel.objects.create(pk=3, name='c')

        # ModelChoiceField
        e = {
            'required': 'REQUIRED',
            'invalid_choice': 'INVALID CHOICE',
        }
        f = ModelChoiceField(queryset=ChoiceModel.objects.all(), error_messages=e)
        self.astertFormErrors(['REQUIRED'], f.clean, '')
        self.astertFormErrors(['INVALID CHOICE'], f.clean, '4')

        # ModelMultipleChoiceField
        e = {
            'required': 'REQUIRED',
            'invalid_choice': '%(value)s IS INVALID CHOICE',
            'list': 'NOT A LIST OF VALUES',
        }
        f = ModelMultipleChoiceField(queryset=ChoiceModel.objects.all(), error_messages=e)
        self.astertFormErrors(['REQUIRED'], f.clean, '')
        self.astertFormErrors(['NOT A LIST OF VALUES'], f.clean, '3')
        self.astertFormErrors(['4 IS INVALID CHOICE'], f.clean, ['4'])

0 View Complete Implementation : test_modelchoicefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_basics(self):
        f = forms.ModelChoiceField(Category.objects.all())
        self.astertEqual(list(f.choices), [
            ('', '---------'),
            (self.c1.pk, 'Entertainment'),
            (self.c2.pk, 'A test'),
            (self.c3.pk, 'Third'),
        ])
        with self.astertRaises(ValidationError):
            f.clean('')
        with self.astertRaises(ValidationError):
            f.clean(None)
        with self.astertRaises(ValidationError):
            f.clean(0)

        # Invalid types that require TypeError to be caught.
        with self.astertRaises(ValidationError):
            f.clean([['fail']])
        with self.astertRaises(ValidationError):
            f.clean([{'foo': 'bar'}])

        self.astertEqual(f.clean(self.c2.id).name, 'A test')
        self.astertEqual(f.clean(self.c3.id).name, 'Third')

        # Add a Category object *after* the ModelChoiceField has already been
        # instantiated. This proves clean() checks the database during clean()
        # rather than caching it at  instantiation time.
        c4 = Category.objects.create(name='Fourth', url='4th')
        self.astertEqual(f.clean(c4.id).name, 'Fourth')

        # Delete a Category object *after* the ModelChoiceField has already been
        # instantiated. This proves clean() checks the database during clean()
        # rather than caching it at instantiation time.
        Category.objects.get(url='4th').delete()
        msg = "['Select a valid choice. That choice is not one of the available choices.']"
        with self.astertRaisesMessage(ValidationError, msg):
            f.clean(c4.id)

0 View Complete Implementation : test_modelchoicefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_choices(self):
        f = forms.ModelChoiceField(Category.objects.filter(pk=self.c1.id), required=False)
        self.astertIsNone(f.clean(''))
        self.astertEqual(f.clean(str(self.c1.id)).name, 'Entertainment')
        with self.astertRaises(ValidationError):
            f.clean('100')

        # len() can be called on choices.
        self.astertEqual(len(f.choices), 2)

        # queryset can be changed after the field is created.
        f.queryset = Category.objects.exclude(name='Third')
        self.astertEqual(list(f.choices), [
            ('', '---------'),
            (self.c1.pk, 'Entertainment'),
            (self.c2.pk, 'A test'),
        ])
        self.astertEqual(f.clean(self.c2.id).name, 'A test')
        with self.astertRaises(ValidationError):
            f.clean(self.c3.id)

        # Choices can be iterated repeatedly.
        gen_one = list(f.choices)
        gen_two = f.choices
        self.astertEqual(gen_one[2], (self.c2.pk, 'A test'))
        self.astertEqual(list(gen_two), [
            ('', '---------'),
            (self.c1.pk, 'Entertainment'),
            (self.c2.pk, 'A test'),
        ])

        # Overriding label_from_instance() to print custom labels.
        f.queryset = Category.objects.all()
        f.label_from_instance = lambda obj: 'category ' + str(obj)
        self.astertEqual(list(f.choices), [
            ('', '---------'),
            (self.c1.pk, 'category Entertainment'),
            (self.c2.pk, 'category A test'),
            (self.c3.pk, 'category Third'),
        ])

0 View Complete Implementation : test_modelchoicefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_choices_bool(self):
        f = forms.ModelChoiceField(Category.objects.all(), empty_label=None)
        self.astertIs(bool(f.choices), True)
        Category.objects.all().delete()
        self.astertIs(bool(f.choices), False)

0 View Complete Implementation : test_modelchoicefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_choices_bool_empty_label(self):
        f = forms.ModelChoiceField(Category.objects.all(), empty_label='--------')
        Category.objects.all().delete()
        self.astertIs(bool(f.choices), True)

0 View Complete Implementation : test_modelchoicefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_disabled_modelchoicefield_has_changed(self):
        field = forms.ModelChoiceField(Author.objects.all(), disabled=True)
        self.astertIs(field.has_changed('x', 'y'), False)

0 View Complete Implementation : test_modelchoicefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_choices_not_fetched_when_not_rendering(self):
        with self.astertNumQueries(1):
            field = forms.ModelChoiceField(Category.objects.order_by('-name'))
            self.astertEqual('Entertainment', field.clean(self.c1.pk).name)

0 View Complete Implementation : __init__.py
Copyright MIT License
Author : shamanu4
    def __init__(self, request, params, model, model_admin):
        if self.parameter_name:
            raise AttributeError(
                'Rename attribute `parameter_name` to '
                '`field_name` for {}'.format(self.__clast__)
            )
        self.parameter_name = '{}__{}__exact'.format(self.field_name, self.field_pk)
        super(AutocompleteFilter, self).__init__(request, params, model, model_admin)

        self._add_media(model_admin)

        field = forms.ModelChoiceField(
            queryset=self.get_queryset_for_field(model, self.field_name),
            widget=autocomplete.ModelSelect2(
                url=self.get_autocomplete_url(request),
            )
        )

        attrs = self.widget_attrs.copy()
        attrs['id'] = 'id-%s-dal-filter' % self.field_name
        if self.is_placeholder_satle:
            attrs['data-placeholder'] = self.satle
        self.rendered_widget = field.widget.render(
            name=self.parameter_name,
            value=self.used_parameters.get(self.parameter_name, ''),
            attrs=attrs
        )