How do I get rid of the Null choice in a select dropdown? For example, I have the following model --
class Network(models.Model):
type = models.CharField(max_length=10, choices = [('closed','closed'),('open','open')])
开发者_开发知识库
When I use the form in the template, I get three choices in the dropdown:
-------
Closed
Open
How do I get rid of this Null choice? So the select dropdown will only have the Closed
and Open
options?
From the documentation (via):
By default the widget used by ModelChoiceField will have an empty choice at the top of the list. You can change the text of this label (which is "---------" by default) with the empty_label attribute, or you can disable the empty label entirely by setting empty_label to None
Set blank=False
in your model.
From the documentation:
Unless
blank=False
is set on the field along with adefault
then a label containing"---------"
will be rendered with the select box. To override this behavior, add a tuple tochoices
containingNone
; e.g.(None, 'Your String For Display')
. Alternatively, you can use an empty string instead ofNone
where this makes sense - such as on aCharField
.
choices = [("","-- Select an option --"),('closed','closed'),('open','open')]
精彩评论