本文整理汇总了Python中django.forms.CharField.choices方法的典型用法代码示例。如果您正苦于以下问题:Python CharField.choices方法的具体用法?Python CharField.choices怎么用?Python CharField.choices使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.forms.CharField
的用法示例。
在下文中一共展示了CharField.choices方法的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_ordering_field
# 需要导入模块: from django.forms import CharField [as 别名]
# 或者: from django.forms.CharField import choices [as 别名]
def get_ordering_field(self):
"""
Fixed get_ordering_field to not depend on self.filters because we
overwrite them when accessing self.qs.
"""
ordering_field = super(FilterSet, self).get_ordering_field()
if self._meta.order_by is True:
if getattr(self, "default_order", None):
choices = [(",".join(self.default_order),) * 2]
else:
choices = []
for field in self._meta.model._meta.get_fields(): # pylint: disable=protected-access
label = getattr(field, "verbose_name", field.name.capitalize())
choices += [
(field.name, label),
("-{}".format(field.name), "{} (descending)".format(label))
]
def validator_factory(queryset):
def validate_order_by(value):
ordered_queryset = queryset.order_by(*value.split(","))
compiler = ordered_queryset.query.get_compiler(using=ordered_queryset.db)
try:
compiler.get_order_by()
except FieldError:
raise ValidationError("'{}' is not a valid order".format(value))
return validate_order_by
ordering_field = CharField(
label=ordering_field.label,
required=False,
widget=Select,
validators=[validator_factory(self.queryset)])
ordering_field.choices = choices
ordering_field.widget.choices = choices
return ordering_field