当前位置: 首页>>代码示例>>Python>>正文


Python forms.ModelChoiceField方法代码示例

本文整理汇总了Python中django.forms.ModelChoiceField方法的典型用法代码示例。如果您正苦于以下问题:Python forms.ModelChoiceField方法的具体用法?Python forms.ModelChoiceField怎么用?Python forms.ModelChoiceField使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在django.forms的用法示例。


在下文中一共展示了forms.ModelChoiceField方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: staff_products_form_factory

# 需要导入模块: from django import forms [as 别名]
# 或者: from django.forms import ModelChoiceField [as 别名]
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 
开发者ID:chrisjrn,项目名称:registrasion,代码行数:25,代码来源:forms.py

示例2: get_modelinstance_form

# 需要导入模块: from django import forms [as 别名]
# 或者: from django.forms import ModelChoiceField [as 别名]
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 
开发者ID:whyflyru,项目名称:django-seo,代码行数:27,代码来源:admin.py

示例3: build_presentation_field

# 需要导入模块: from django import forms [as 别名]
# 或者: from django.forms import ModelChoiceField [as 别名]
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) 
开发者ID:pydata,项目名称:conf_site,代码行数:18,代码来源:forms.py

示例4: formfield

# 需要导入模块: from django import forms [as 别名]
# 或者: from django.forms import ModelChoiceField [as 别名]
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) 
开发者ID:tejoesperanto,项目名称:pasportaservo,代码行数:23,代码来源:fields.py

示例5: make_role_reviewer_fields

# 需要导入模块: from django import forms [as 别名]
# 或者: from django.forms import ModelChoiceField [as 别名]
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 
开发者ID:OpenTechFund,项目名称:hypha,代码行数:23,代码来源:forms.py

示例6: test_prefetch_related_queryset

# 需要导入模块: from django import forms [as 别名]
# 或者: from django.forms import ModelChoiceField [as 别名]
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'),
            )) 
开发者ID:nesdis,项目名称:djongo,代码行数:24,代码来源:tests.py

示例7: test_overridable_choice_iterator

# 需要导入模块: from django import forms [as 别名]
# 或者: from django.forms import ModelChoiceField [as 别名]
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) 
开发者ID:nesdis,项目名称:djongo,代码行数:18,代码来源:test_modelchoicefield.py

示例8: test_choices_freshness

# 需要导入模块: from django import forms [as 别名]
# 或者: from django.forms import ModelChoiceField [as 别名]
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'),
        ]) 
开发者ID:nesdis,项目名称:djongo,代码行数:20,代码来源:test_modelchoicefield.py

示例9: _set_up_relay_vlan

# 需要导入模块: from django import forms [as 别名]
# 或者: from django.forms import ModelChoiceField [as 别名]
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
        ) 
开发者ID:maas,项目名称:maas,代码行数:20,代码来源:vlan.py

示例10: statuses

# 需要导入模块: from django import forms [as 别名]
# 或者: from django.forms import ModelChoiceField [as 别名]
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'])) 
开发者ID:fpsw,项目名称:Servo,代码行数:11,代码来源:queue.py

示例11: __init__

# 需要导入模块: from django import forms [as 别名]
# 或者: from django.forms import ModelChoiceField [as 别名]
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,
        ) 
开发者ID:GamesDoneQuick,项目名称:donation-tracker,代码行数:10,代码来源:forms.py

示例12: make_value_field

# 需要导入模块: from django import forms [as 别名]
# 或者: from django.forms import ModelChoiceField [as 别名]
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 
开发者ID:sfu-fas,项目名称:coursys,代码行数:10,代码来源:search.py

示例13: __init__

# 需要导入模块: from django import forms [as 别名]
# 或者: from django.forms import ModelChoiceField [as 别名]
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) 
开发者ID:sfu-fas,项目名称:coursys,代码行数:7,代码来源:forms.py

示例14: __init__

# 需要导入模块: from django import forms [as 别名]
# 或者: from django.forms import ModelChoiceField [as 别名]
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) 
开发者ID:JamesRamm,项目名称:longclaw,代码行数:17,代码来源:forms.py

示例15: formfield

# 需要导入模块: from django import forms [as 别名]
# 或者: from django.forms import ModelChoiceField [as 别名]
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) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:15,代码来源:related.py


注:本文中的django.forms.ModelChoiceField方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。