You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django表单ModelChoiceField选项显示元组格式如何解决?

问题:Django ModelForm中Select字段显示元组,模板索引访问报错

用户编写的Django ModelForm代码如下:

class AddUserGroupFrom(forms.ModelForm):
    class Meta:
        model = UsersGroups
        fields = (
            'tag',
        )
        widgets = {
            'tag': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Work, home, etc..'}),
        }
    
    def __init__(self, *args, **kwargs):
        super(AddUserGroupFrom, self).__init__(*args, **kwargs)
        self.fields['city'] = forms.ModelChoiceField(
            queryset=Group.objects.values_list('city').all().distinct(),
            widget=forms.Select(attrs={
                'class': 'form-select form-select-sm mb-3',
                'aria-label': '.form-select-sm example',
            }),
            label='Choose city name',
            empty_label='Select city',
        )
        self.fields['group'] = forms.ModelChoiceField(
            queryset=Group.objects.values_list('group_number').all(),
            widget=forms.Select(attrs={
                'class': 'form-select form-select-sm mb-3',
                'aria-label': '.form-select-sm example',
            }),
            label='Choose group number',
            empty_label='Select group',
        )

对应的模板代码:

<form action="" method="post">
        {% csrf_token %}

        <div class="mb-3">
            <label for="{{ add_group_form.tag.id_for_label }}" class="form-label">{{ add_group_form.tag.label }}</label>
            {{ add_group_form.tag }}
        </div>

        <label for="{{ add_group_form.city.id_for_label }}">{{ add_group_form.city.label }}</label>
        {{ add_group_form.city }}

        <label for="{{ add_group_form.group.id_for_label }}">{{ add_group_form.group.label }}</label>
        {{ add_group_form.group }}

        <input type="submit" value="Save changes" class="btn btn-success">
    </form>

遇到的问题:

  • Select字段的选项以元组形式显示
  • 尝试在模板中使用{{ add_group_form.city[0] }}索引访问时,出现错误:

Could not parse the remainder: '[0]' from 'add_group_form.city[0]'


解决方法

1. 去除Select选项的元组显示

问题根源是values_list()默认返回元组(即便只指定单个字段)。只需在调用values_list()时添加flat=True参数,即可返回单个值而非元组:

修改ModelForm中两个字段的queryset:

# city字段修改后
self.fields['city'] = forms.ModelChoiceField(
    queryset=Group.objects.values_list('city', flat=True).distinct(),
    widget=forms.Select(attrs={
        'class': 'form-select form-select-sm mb-3',
        'aria-label': '.form-select-sm example',
    }),
    label='Choose city name',
    empty_label='Select city',
)

# group字段修改后
self.fields['group'] = forms.ModelChoiceField(
    queryset=Group.objects.values_list('group_number', flat=True).all(),
    widget=forms.Select(attrs={
        'class': 'form-select form-select-sm mb-3',
        'aria-label': '.form-select-sm example',
    }),
    label='Choose group number',
    empty_label='Select group',
)

2. 模板索引访问的正确语法

Django模板不支持[0]的索引写法,若需要访问字段的索引值,应使用.0的格式,例如:

{{ add_group_form.city.0 }}

不过解决元组显示问题后,该索引访问通常不再需要,因为选项已变为正常的单个值。


内容的提问来源于stack exchange,提问作者Музика Андрій

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 09:31:00