![](/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.