Python django.forms.ModelChoiceField() Examples

The following are 30 code examples for showing how to use django.forms.ModelChoiceField(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.forms , or try the search function .

Example 1
Project: django-seo   Author: whyflyru   File: admin.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_modelinstance_form(metadata_class):
    model_class = metadata_class._meta.get_model('modelinstance')

    # Restrict content type choices to the models set in seo_models
    content_types = get_seo_content_types(metadata_class._meta.seo_models)

    # Get a list of fields, with _content_type at the start
    important_fields = ['_content_type'] + ['_object_id'] + core_choice_fields(metadata_class)
    _fields = important_fields + list(fields_for_model(model_class,
                                                  exclude=important_fields).keys())

    class ModelMetadataForm(forms.ModelForm):
        _content_type = forms.ModelChoiceField(
            queryset=ContentType.objects.filter(id__in=content_types),
            empty_label=None,
            label=capfirst(_("model")),
        )

        _object_id = forms.IntegerField(label=capfirst(_("ID")))

        class Meta:
            model = model_class
            fields = _fields

    return ModelMetadataForm 
Example 2
Project: conf_site   Author: pydata   File: forms.py    License: MIT License 6 votes vote down vote up
def build_presentation_field(self):
        kwargs = {}
        queryset = Presentation.objects.all()
        queryset = queryset.exclude(cancelled=True)
        queryset = queryset.order_by("proposal_base__pk")
        if self.slot.content:
            queryset = queryset.filter(
                Q(slot=None) | Q(pk=self.slot.content.pk)
            )
            kwargs["required"] = False
            kwargs["initial"] = self.slot.content
        else:
            queryset = queryset.filter(slot=None)
            kwargs["required"] = True
        kwargs["queryset"] = queryset
        return forms.ModelChoiceField(**kwargs) 
Example 3
Project: pasportaservo   Author: tejoesperanto   File: fields.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def formfield(self, **kwargs):
        class SuggestiveModelChoiceFormField(forms.ModelChoiceField):
            widget = TextWithDatalistInput

            def __init__(self, *args, **kwargs):
                super().__init__(*args, **kwargs)
                self.empty_label = None

            def to_python(self, value):
                converted_value, is_invalid = _handle_invalid_choice(self, value, function='to_python')
                if is_invalid:
                    data = {'pk': value}
                    if self.to_field_name and self.to_field_name != 'pk':
                        data.update({self.to_field_name: value})
                        data['pk'] = -1
                    converted_value = self.queryset.model(**data)
                return converted_value

        defaults = {'form_class': SuggestiveModelChoiceFormField}
        defaults.update(kwargs)
        return super().formfield(**defaults) 
Example 4
Project: registrasion   Author: chrisjrn   File: forms.py    License: Apache License 2.0 6 votes vote down vote up
def staff_products_form_factory(user):
    ''' Creates a StaffProductsForm that restricts the available products to
    those that are available to a user. '''

    products = inventory.Product.objects.all()
    products = ProductController.available_products(user, products=products)

    product_ids = [product.id for product in products]
    product_set = inventory.Product.objects.filter(id__in=product_ids)

    class StaffProductsForm(forms.Form):
        ''' Form for allowing staff to add an item to a user's cart. '''

        product = forms.ModelChoiceField(
            widget=forms.Select,
            queryset=product_set,
        )

        quantity = forms.IntegerField(
            min_value=0,
        )

    return StaffProductsForm 
Example 5
Project: hypha   Author: OpenTechFund   File: forms.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def make_role_reviewer_fields():
    role_fields = []
    staff_reviewers = User.objects.staff().only('full_name', 'pk')

    for role in ReviewerRole.objects.all().order_by('order'):
        field_name = 'role_reviewer_' + slugify(str(role))
        field = forms.ModelChoiceField(
            queryset=staff_reviewers,
            widget=Select2Widget(attrs={
                'data-placeholder': 'Select a reviewer',
            }),
            required=False,
            label=mark_safe(render_icon(role.icon) + f'{role.name} Reviewer'),
        )
        role_fields.append({
            'role': role,
            'field': field,
            'field_name': field_name,
        })

    return role_fields 
Example 6
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_prefetch_related_queryset(self):
        """
        ModelChoiceField should respect a prefetch_related() on its queryset.
        """
        blue = Colour.objects.create(name='blue')
        red = Colour.objects.create(name='red')
        multicolor_item = ColourfulItem.objects.create()
        multicolor_item.colours.add(blue, red)
        red_item = ColourfulItem.objects.create()
        red_item.colours.add(red)

        class ColorModelChoiceField(forms.ModelChoiceField):
            def label_from_instance(self, obj):
                return ', '.join(c.name for c in obj.colours.all())

        field = ColorModelChoiceField(ColourfulItem.objects.prefetch_related('colours'))
        with self.assertNumQueries(3):  # would be 4 if prefetch is ignored
            self.assertEqual(tuple(field.choices), (
                ('', '---------'),
                (multicolor_item.pk, 'blue, red'),
                (red_item.pk, 'red'),
            )) 
Example 7
Project: djongo   Author: nesdis   File: test_modelchoicefield.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_overridable_choice_iterator(self):
        """
        Iterator defaults to ModelChoiceIterator and can be overridden with
        the iterator attribute on a ModelChoiceField subclass.
        """
        field = forms.ModelChoiceField(Category.objects.all())
        self.assertIsInstance(field.choices, ModelChoiceIterator)

        class CustomModelChoiceIterator(ModelChoiceIterator):
            pass

        class CustomModelChoiceField(forms.ModelChoiceField):
            iterator = CustomModelChoiceIterator

        field = CustomModelChoiceField(Category.objects.all())
        self.assertIsInstance(field.choices, CustomModelChoiceIterator) 
Example 8
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_prefetch_related_queryset(self):
        """
        ModelChoiceField should respect a prefetch_related() on its queryset.
        """
        blue = Colour.objects.create(name='blue')
        red = Colour.objects.create(name='red')
        multicolor_item = ColourfulItem.objects.create()
        multicolor_item.colours.add(blue, red)
        red_item = ColourfulItem.objects.create()
        red_item.colours.add(red)

        class ColorModelChoiceField(forms.ModelChoiceField):
            def label_from_instance(self, obj):
                return ', '.join(c.name for c in obj.colours.all())

        field = ColorModelChoiceField(ColourfulItem.objects.prefetch_related('colours'))
        with self.assertNumQueries(3):  # would be 4 if prefetch is ignored
            self.assertEqual(tuple(field.choices), (
                ('', '---------'),
                (multicolor_item.pk, 'blue, red'),
                (red_item.pk, 'red'),
            )) 
Example 9
Project: djongo   Author: nesdis   File: test_modelchoicefield.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_choices_freshness(self):
        f = forms.ModelChoiceField(Category.objects.all())
        self.assertEqual(len(f.choices), 4)
        self.assertEqual(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.assertEqual(len(f.choices), 5)
        self.assertEqual(list(f.choices), [
            ('', '---------'),
            (self.c1.pk, 'Entertainment'),
            (self.c2.pk, 'A test'),
            (self.c3.pk, 'Third'),
            (c4.pk, 'Fourth'),
        ]) 
Example 10
Project: djongo   Author: nesdis   File: test_modelchoicefield.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_overridable_choice_iterator(self):
        """
        Iterator defaults to ModelChoiceIterator and can be overridden with
        the iterator attribute on a ModelChoiceField subclass.
        """
        field = forms.ModelChoiceField(Category.objects.all())
        self.assertIsInstance(field.choices, ModelChoiceIterator)

        class CustomModelChoiceIterator(ModelChoiceIterator):
            pass

        class CustomModelChoiceField(forms.ModelChoiceField):
            iterator = CustomModelChoiceIterator

        field = CustomModelChoiceField(Category.objects.all())
        self.assertIsInstance(field.choices, CustomModelChoiceIterator) 
Example 11
Project: maas   Author: maas   File: vlan.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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
        ) 
Example 12
Project: Servo   Author: fpsw   File: queue.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def statuses(request, queue_id):
    """Lists available statuses for this queue"""
    queue = Queue.objects.get(pk=queue_id)
    
    class StatusForm(forms.Form):
        status = forms.ModelChoiceField(queryset=queue.queuestatus_set.all())

    form = StatusForm()
    return HttpResponse(str(form['status'])) 
Example 13
Project: donation-tracker   Author: GamesDoneQuick   File: forms.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, event=None, allow_empty=True, *args, **kwargs):
        super(EventFilterForm, self).__init__(*args, **kwargs)
        self.fields['event'] = forms.ModelChoiceField(
            queryset=models.Event.objects.all(),
            empty_label='All Events',
            initial=event,
            required=not allow_empty,
        ) 
Example 14
Project: coursys   Author: sfu-fas   File: search.py    License: GNU General Public License v3.0 5 votes vote down vote up
def make_value_field(self, viewer, member_units):
        field = super(ChoiceSearchRule, self).make_value_field(viewer, member_units)

        if self.field.required and not isinstance(self.field, forms.ModelChoiceField):
            field.choices = (('', mark_safe('—')),) + tuple(field.choices)
        field.initial = ''

        return field 
Example 15
Project: coursys   Author: sfu-fas   File: forms.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        fields = [forms.ModelChoiceField(Account.objects.all()) for _ in CATEGORY_CHOICES]
        kwargs['fields'] = fields
        kwargs['widget'] = AccountsWidget()
        super(AccountsField, self).__init__(*args, **kwargs) 
Example 16
Project: longclaw   Author: JamesRamm   File: forms.py    License: MIT License 5 votes vote down vote up
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) 
Example 17
Project: GTDWeb   Author: lanbing510   File: related.py    License: GNU General Public License v2.0 5 votes vote down vote up
def formfield(self, **kwargs):
        db = kwargs.pop('using', None)
        if isinstance(self.rel.to, six.string_types):
            raise ValueError("Cannot create form field for %r yet, because "
                             "its related model %r has not been loaded yet" %
                             (self.name, self.rel.to))
        defaults = {
            'form_class': forms.ModelChoiceField,
            'queryset': self.rel.to._default_manager.using(db),
            'to_field_name': self.rel.field_name,
        }
        defaults.update(kwargs)
        return super(ForeignKey, self).formfield(**defaults) 
Example 18
Project: casepro   Author: rapidpro   File: forms.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        org = kwargs.pop("org")
        org_fields = Field.get_all(org).order_by("label")

        fields = (
            forms.ModelChoiceField(queryset=org_fields, required=False, to_field_name="key"),
            forms.CharField(max_length=64),
        )
        widgets = (fields[0].widget, fields[1].widget)

        super(FieldTestField, self).__init__(fields, *args, **kwargs)

        self.widget = FieldTestWidget(widgets) 
Example 19
Project: bioforum   Author: reBiocoder   File: related.py    License: MIT License 5 votes vote down vote up
def formfield(self, *, using=None, **kwargs):
        if isinstance(self.remote_field.model, str):
            raise ValueError("Cannot create form field for %r yet, because "
                             "its related model %r has not been loaded yet" %
                             (self.name, self.remote_field.model))
        defaults = {
            'form_class': forms.ModelChoiceField,
            'queryset': self.remote_field.model._default_manager.using(using),
            'to_field_name': self.remote_field.field_name,
        }
        defaults.update(kwargs)
        return super().formfield(**defaults) 
Example 20
Project: dissemin   Author: dissemin   File: forms.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def _get_choices(self):
        """
        Exactly as per ModelChoiceField except returns new iterator class
        """
        if hasattr(self, '_choices'):
            return self._choices
        return ModelGroupedChoiceIterator(self) 
Example 21
Project: dal_admin_filters   Author: shamanu4   File: __init__.py    License: MIT License 5 votes vote down vote up
def __init__(self, request, params, model, model_admin):
        if self.parameter_name:
            raise AttributeError(
                'Rename attribute `parameter_name` to '
                '`field_name` for {}'.format(self.__class__)
            )
        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_title:
            attrs['data-placeholder'] = self.title
        self.rendered_widget = field.widget.render(
            name=self.parameter_name,
            value=self.used_parameters.get(self.parameter_name, ''),
            attrs=attrs
        ) 
Example 22
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: related.py    License: MIT License 5 votes vote down vote up
def formfield(self, *, using=None, **kwargs):
        if isinstance(self.remote_field.model, str):
            raise ValueError("Cannot create form field for %r yet, because "
                             "its related model %r has not been loaded yet" %
                             (self.name, self.remote_field.model))
        return super().formfield(**{
            'form_class': forms.ModelChoiceField,
            'queryset': self.remote_field.model._default_manager.using(using),
            'to_field_name': self.remote_field.field_name,
            **kwargs,
        }) 
Example 23
Project: wagtail   Author: wagtail   File: field_block.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def field(self):
        return forms.ModelChoiceField(
            queryset=self.target_model.objects.all(), widget=self.widget, required=self._required,
            validators=self._validators,
            help_text=self._help_text) 
Example 24
Project: wagtail   Author: wagtail   File: field_block.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def value_from_form(self, value):
        # ModelChoiceField sometimes returns an ID, and sometimes an instance; we want the instance
        if value is None or isinstance(value, self.target_model):
            return value
        else:
            try:
                return self.target_model.objects.get(pk=value)
            except self.target_model.DoesNotExist:
                return None 
Example 25
Project: wagtail   Author: wagtail   File: field_block.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def clean(self, value):
        # ChooserBlock works natively with model instances as its 'value' type (because that's what you
        # want to work with when doing front-end templating), but ModelChoiceField.clean expects an ID
        # as the input value (and returns a model instance as the result). We don't want to bypass
        # ModelChoiceField.clean entirely (it might be doing relevant validation, such as checking page
        # type) so we convert our instance back to an ID here. It means we have a wasted round-trip to
        # the database when ModelChoiceField.clean promptly does its own lookup, but there's no easy way
        # around that...
        if isinstance(value, self.target_model):
            value = value.pk
        return super().clean(value) 
Example 26
Project: django-leonardo   Author: django-leonardo   File: forms.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def init_color_scheme_switch(self, color_scheme=None, field_kwargs={}):
        color_scheme_fields = []

        for theme in self.fields['theme'].queryset:

            name = 'theme__%s' % theme.id
            attributes = self.get_switched_form_field_attrs(
                'switchable', '%s' % theme.id, ('Color Scheme'))
            field = django_forms.ModelChoiceField(
                label=_('Color Scheme'),
                queryset=theme.templates.all(),
                required=False,
                **field_kwargs)
            # inital for color scheme
            if color_scheme and theme.templates.filter(
                    id=color_scheme.id).exists():
                field.initial = color_scheme
            elif 'parent' in self.fields and self.fields['parent'].initial:
                field.initial = self.fields['parent'].initial.color_scheme
            elif hasattr(self, 'instance') \
                    and hasattr(self.instance, 'color_scheme'):
                field.initial = self.instance.color_scheme
            else:
                field.initial = theme.templates.first()
            field.widget.attrs = attributes
            self.fields[name] = field
            color_scheme_fields.append(name)

        # update theme widget attributes
        self.fields['theme'].widget.attrs = self.switchable_field_attrs()
        return color_scheme_fields 
Example 27
Project: Spirit   Author: nitely   File: forms.py    License: MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(CategoryForm, self).__init__(*args, **kwargs)
        queryset = Category.objects.visible().parents()

        if self.instance.pk:
            queryset = queryset.exclude(pk=self.instance.pk)

        self.fields['parent'] = forms.ModelChoiceField(
            queryset=queryset, required=False)
        self.fields['parent'].label_from_instance = (
            lambda obj: smart_text(obj.title)) 
Example 28
Project: python   Author: Yeah-Kun   File: related.py    License: Apache License 2.0 5 votes vote down vote up
def formfield(self, **kwargs):
        db = kwargs.pop('using', None)
        if isinstance(self.remote_field.model, six.string_types):
            raise ValueError("Cannot create form field for %r yet, because "
                             "its related model %r has not been loaded yet" %
                             (self.name, self.remote_field.model))
        defaults = {
            'form_class': forms.ModelChoiceField,
            'queryset': self.remote_field.model._default_manager.using(db),
            'to_field_name': self.remote_field.field_name,
        }
        defaults.update(kwargs)
        return super(ForeignKey, self).formfield(**defaults) 
Example 29
Project: yournextrepresentative   Author: mysociety   File: forms.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        include_historic = kwargs.pop('include_historic')
        super(AddCandidacyPickElectionForm, self).__init__(*args, **kwargs)
        election_qs = Election.objects.order_by('-election_date', 'name')
        if not include_historic:
            election_qs = election_qs.filter(current=True)
        self.fields['election'] = forms.ModelChoiceField(queryset=election_qs) 
Example 30
Project: luscan-devel   Author: blackye   File: related.py    License: GNU General Public License v2.0 5 votes vote down vote up
def formfield(self, **kwargs):
        db = kwargs.pop('using', None)
        if isinstance(self.rel.to, six.string_types):
            raise ValueError("Cannot create form field for %r yet, because "
                             "its related model %r has not been loaded yet" %
                             (self.name, self.rel.to))
        defaults = {
            'form_class': forms.ModelChoiceField,
            'queryset': self.rel.to._default_manager.using(db).complex_filter(self.rel.limit_choices_to),
            'to_field_name': self.rel.field_name,
        }
        defaults.update(kwargs)
        return super(ForeignKey, self).formfield(**defaults)