當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。