![](/img/trans.png)
[英]How do I filter the choices in a ModelForm that has a CharField with the choices attribute (and hence a Select Field)
[英]In a Django ModelForm, I want to display a CharField as a Select Field with defined choices
我正在尝试按照Django网站上的文档来覆盖表单的默认格式。 我已经尝试了多种解决方案(全部都注释掉了,它们给了我一个错误)。 非注释部分有效,但仅呈现选择框而没有任何选择。 您能告诉我我做错了吗?
def get_site_geographies():
return Site.objects.values_list('site_geography', flat=True).distinct()
class SiteFilterForm(forms.ModelForm):
class Meta:
model = Site
fields = ['site_geography', 'site_region', 'site_name']
# field_classes = {
# 'site_geography': forms.ChoiceField(choices=get_site_geographies())
# }
widgets = {
'site_geography': forms.Select
# widgets = {
# 'site_geography': forms.ChoiceField(choices=get_site_geographies())
# }
在models.py中,这是我指的相关模型字段:
class Site (models.Model):
site_name = models.CharField(max_length=255)
site_geography = models.CharField(max_length=255)
site_region = models.CharField(max_length=255, blank=True)
选项选项需要迭代。 2元组的列表或元组,其格式为:
(value, value to display)
因此,您需要遍历值并创建此格式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.