Customize/remove Django select box blank option

后端 未结 15 883
佛祖请我去吃肉
佛祖请我去吃肉 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:01

    I was messing around with this today and just came up with a coward hack nifty solution:

    # Cowardly handle ModelChoiceField empty label
    # we all hate that '-----' thing
    class ModelChoiceField_init_hack(object):
        @property
        def empty_label(self):
            return self._empty_label
    
        @empty_label.setter
        def empty_label(self, value):
            self._empty_label = value
            if value and value.startswith('-'):
                self._empty_label = 'Select an option'
    ModelChoiceField.__bases__ += (ModelChoiceField_init_hack,)
    

    Now you can tweak the default ModelChoiceField empty label to anything you'd like. :-)

    PS: No need for downvotes, non-harmful monkey patches are always handy.

提交回复
热议问题