开发者

Null field in select dropdown

开发者 https://www.devze.com 2023-03-08 19:59 出处:网络
How do I get rid of the Null choice in a select dropdown? For example, I have the following model -- class Network(models.Model):

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 a default then a label containing "---------" will be rendered with the select box. To override this behavior, add a tuple to choices containing None; e.g. (None, 'Your String For Display'). Alternatively, you can use an empty string instead of None where this makes sense - such as on a CharField.


choices = [("","-- Select an option --"),('closed','closed'),('open','open')]
0

精彩评论

暂无评论...
验证码 换一张
取 消