ModelChoiceField , removing the blank choice

后端 未结 1 1558
时光取名叫无心
时光取名叫无心 2021-01-01 15:27

I want to get rid of the \"-------------\" choice Django adds in a select input representing a Foreign Key on a ModelForm

It\'s been answered that you can use the

相关标签:
1条回答
  • If you want to remove the blank choice for all ModelChoiceField you could do something like..

    class Form(forms.ModelForm):
        class Meta:
            model = MyModel
    
        def __init__(self, *args, **kwargs):
            super(Form, self).__init__(*args, **kwargs)
            modelchoicefields = [field for field_name, field in self.fields.iteritems() if
                isinstance(field, forms.ModelChoiceField)]
    
            for field in modelchoicefield:
                field.empty_label = None
    

    But that would replace all ModelChoiceFields, so maybe something more fine grained like:

    for fieldname in ('field1','field2','field3','field4','field5','field6'):
        self.fields[fieldname].empty_label = None
    

    Certainly easier than the __init__ overwrite you mentioned!

    Update from Moritz

    You can use 2017+ use:

    forms.ModelChoiceField(... empty_label=None
    
    0 讨论(0)
提交回复
热议问题