Customize/remove Django select box blank option

后端 未结 15 860
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-30 18:22

I\'m using Django 1.0.2. I\'ve written a ModelForm backed by a Model. This model has a ForeignKey where blank=False. When Django generates HTML for this form it creates a

15条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-30 19:05

    There are lots of great answers here, but I'm still not entirely satisfied with the implementations. I'm also a bit frustrated that select widgets from different sources (foreign keys, choices) yield different behaviours.

    I have a design I'm working with where select fields always have a blank option, and if they're required they will have a star next to them and the form will simply not validate if they're left empty. That said, I can only properly override the empty_label for fields that are not TypedChoiceFields.

    Here's what the result should look like. The first result is always the name of the field - in my case, the label.

    Here's what I ended up doing. The following is an overridden __init__ method of my form:

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for _, field in self.fields.items():
            if hasattr(field, 'empty_label'):
                field.empty_label = field.label
            if isinstance(field, forms.TypedChoiceField):
                field.choices = [('', field.label)] + [choice for choice in field.choices if choice[0]]
    

提交回复
热议问题