我试图按照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.
更多推荐
发布评论