本文整理汇总了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
示例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
示例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)
示例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)
示例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
示例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'),
))
示例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)
示例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'),
])
示例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
)
示例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']))
示例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,
)
示例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
示例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)
示例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)
示例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)