在Django ModelForm中,我想将CharField显示为具有已定义选项的Select Field(In a Django ModelForm, I want to display a Ch

编程入门 行业动态 更新时间:2024-10-14 10:37:35
在Django ModelForm中,我想将CharField显示为具有已定义选项的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)

I am trying to follow the documentation on the Django site to overwrite the default formatting of the form. I have tried a number of solutions (all commented out and they give me an error). The non-commented section, works but just renders a select box without any choices. Could you please let me know what I am doing wrong?

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()) # }

In models.py, this is the relevant model field that I am referring to:

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)

因此,您需要迭代您的值并创建此格式。

The choices options takes an iterable. A list or tuple of 2-tuples, which would be of the format:

(value, value to display)

So, you need to iterate over your values and create this format.

更多推荐

本文发布于:2023-07-30 18:27:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1338874.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:想将   选项   定义   CharField   ModelForm

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!