私信  •  关注

Mithril

Mithril 最近创建的主题
Mithril 最近回复了
9 年前
回复了 Mithril 创建的主题 » 自定义/删除Django选择框空白选项

self.fields['xxx'].empty_value = None 如果字段类型为 TypedChoiceField 哪个没有 empty_label 财产。

我们应该做的是删除第一选择:

1。如果你想建立一个 BaseForm 自动检测 类型dchoicefield

class BaseForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(BaseForm, self).__init__(*args, **kwargs)

        for field_name in self.fields:
            field = self.fields.get(field_name)
            if field and isinstance(field , forms.TypedChoiceField):
                field.choices = field.choices[1:]
            # code to process other Field
            # ....

class AddClientForm(BaseForm):
     pass

2.只有几种形式,您可以使用:

class AddClientForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(AddClientForm, self).__init__(*args, **kwargs)
        self.fields['xxx'].choices = self.fields['xxx'].choices[1:]