在Django表单中自定义ModelChoiceField内的选项。

huangapple go评论73阅读模式
英文:

Customize options inside the ModelChoiceField Django forms

问题

我有一个类似这样的Django表单:

class AddUserGroupFrom(forms.ModelForm):
    class Meta:
        model = UsersGroups
        fields = (
            'tag',
        )
        widgets = {
            'tag': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '工作,家庭,等等..'}),
        }
    
    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='选择城市名称',
            empty_label='选择城市',
        )
        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='选择组编号',
            empty_label='选择组',
        )

问题是在我的选择字段中,选项以元组的形式显示。模板如下所示:

<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="保存更改" class="btn btn-success">
</form>

如何删除选择字段内部的元组样式表示?

我尝试在模板中使用索引进行迭代:

{{ add_group_form.city[0] }}

但会抛出错误:

无法解析余额: 'add_group_form.city[0]' 的 '[0]'

英文:

I have a django form like this:

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

The problem that in my select field options displayed as tuples
Form representation
Templates look like this:

&lt;form action=&quot;&quot; method=&quot;post&quot;&gt;
        {% csrf_token %}

        &lt;div class=&quot;mb-3&quot;&gt;
            &lt;label for=&quot;{{ add_group_form.tag.id_for_label }}&quot; class=&quot;form-label&quot;&gt;{{ add_group_form.tag.label }}&lt;/label&gt;
            {{ add_group_form.tag }}
        &lt;/div&gt;

        &lt;label for=&quot;{{ add_group_form.city.id_for_label }}&quot;&gt;{{ add_group_form.city.label }}&lt;/label&gt;
        {{ add_group_form.city }}

        &lt;label for=&quot;{{ add_group_form.group.id_for_label }}&quot;&gt;{{ add_group_form.group.label }}&lt;/label&gt;
        {{ add_group_form.group }}

        &lt;input type=&quot;submit&quot; value=&quot;Save changes&quot; class=&quot;btn btn-success&quot;&gt;
    &lt;/form&gt;

How can I remove tuple-style representation in options inside the select field?

I tried to iterate within indexes in templates:
{{ add_group_form.city[0] }}
But it throws error:

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

答案1

得分: 0

你可以创建一个包含城市数值的元组,并将其分配给表单字段的选择项。通常情况下,你不会在init方法中定义表单字段。看起来city不是一个模型字段,这就是为什么我将其更改为ChoiceField

class AddUserGroupFrom(forms.ModelForm):
    city = forms.ChoiceField(
        choices=[],
        empty_label='选择城市',
        label='选择城市名称',
        widget=forms.Select(attrs={
            'class': 'form-select form-select-sm mb-3',
            'aria-label': '.form-select-sm example',
        }),
    )

    group = forms.ModelChoiceField(
        queryset=Group.objects.all(),
        empty_label='选择群组',
        label='选择群组编号',
        widget=forms.Select(attrs={
            'class': 'form-select form-select-sm mb-3',
            'aria-label': '.form-select-sm example',
        }),
    )

    class Meta:
        model = UsersGroups
        fields = ('tag',)
        widgets = {
            'tag': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '工作、家庭等..'}),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        city_list = Group.objects.values_list('city', flat=True)
        city_choices = [(city, city) for city in city_list]
        self.fields['city'].choices = city_choices

请注意,上述代码中的字符串已经翻译成中文。

英文:

You can create a tuple with the city values and assign it to the choices of the form field. Normally you do not define the form fields in the init method. It looks like city is not a model field. That's why I changed it to a ChocieField.
(code is not tested, change it if needed)

class AddUserGroupFrom(forms.ModelForm):
    city = forms.ChoiceField(
        choices=[],
        empty_label=&#39;Select city&#39;,
        label=&#39;Choose city name&#39;,
        widget=forms.Select(attrs={
            &#39;class&#39;: &#39;form-select form-select-sm mb-3&#39;,
            &#39;aria-label&#39;: &#39;.form-select-sm example&#39;,
        }),
    )

    group = forms.ModelChoiceField(
        queryset=Group.objects.all(),
        empty_label=&#39;Select group&#39;,
        label=&#39;Choose group number&#39;,
        widget=forms.Select(attrs={
            &#39;class&#39;: &#39;form-select form-select-sm mb-3&#39;,
            &#39;aria-label&#39;: &#39;.form-select-sm example&#39;,
        }),
    )

    class Meta:
        model = UsersGroups
        fields = (&#39;tag&#39;,)
        widgets = {
            &#39;tag&#39;: forms.TextInput(attrs={&#39;class&#39;: &#39;form-control&#39;, &#39;placeholder&#39;: &#39;Work, home, etc..&#39;}),
        }
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        city_list = Group.objects.values_list(&#39;city&#39;, flat=True)
        city_choices = [(city, city) for city in city_list]
        self.fields[&#39;city&#39;].choices = city_choices

huangapple
  • 本文由 发表于 2023年2月19日 08:28:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75497279.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定