Blank option in required ChoiceField

前端 未结 4 1169
醉梦人生
醉梦人生 2021-02-20 09:35

I want my ChoiceField in ModelForm to have a blank option (------) but it\'s required.

I need to have blank option to prevent user from accidentally skipping the field t

4条回答
  •  北荒
    北荒 (楼主)
    2021-02-20 09:52

    You can also override form's __init__() method and modify the choices field attribute, reasigning a new list of tuples. (This may be useful for dynamic changes):

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['my_field'].choices = [('', '---------')] + self.fields['my_field'].choices
    

提交回复
热议问题