设置字段可选python
After you play around with the admin site for a while, you’ll probably notice a limitation – the edit forms require every field to be filled out, whereas in many cases you’d want certain fields to be optional. Let’s say, for example, that we want our Author
model’s email
field to be optional – that is, a blank string should be allowed. In the real world, you might not have an e-mail address on file for every author.数据库
在管理站点玩了一段时间以后,您可能会注意到一个限制 - 编辑表单须要填写每一个字段,而在许多状况下,您但愿某些字段是可选的。比方说,咱们但愿咱们的Author模型的email字段是可选的 - 也就是说,应该容许空白字符串。 在现实世界中,您可能没有每一个做者的电子邮件地址。express
To specify that the email
field is optional, edit the Author
model (which, as you’ll recall from Chapter 4, lives in mysite/books/models.py
). Simply add blank=True
to the email
field, like so:django
要指定email字段是可选的,需编辑Author模型(你将从第4章回忆起,它位于mysite / books / models.py中)。 只需将 blank= True 添加到电子邮件字段,以下所示:app
class Author(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=40) email = models.EmailField(blank=True) #email字段是可选的,能够为空字符串 def __str__(self): return '{first_name} {last_name}'.format(first_name=self.first_name, last_name=self.last_name)
This tells Django that a blank value is indeed allowed for authors’ e-mail addresses. By default, all fields have blank=False
, which means blank values are not allowed.ide
这告诉django author的email的确能够为空值。默认状况下,全部的字段设置都是 blank=False,使得字段的值不能为空工具
There’s something interesting happening here. Until now, with the exception of the __str__()
method, our models have served as definitions of our database tables – Pythonic expressions of SQL CREATE TABLE
statements, essentially. In adding blank=True
, we have begun expanding our model beyond a simple definition of what the database table looks like.ui
这里有一些有趣的事情,直到如今,除过__str__()方法之外,咱们的模型已做为咱们数据库表的定义——实质上是用python语法,写CREATE TABLE语句。在添加 blank = True时,咱们已经开始扩展咱们的模型,而不是简单地定义数据库表的样子。
spa
Now, our model class is starting to become a richer collection of knowledge about what Author
objects are and what they can do. Not only is the email
field represented by a VARCHAR
column in the database; it’s also an optional field in contexts such as the Django admin site.rest
如今,咱们的模块类开始成为一个富含Author对象属性和行为的集合了。 email不但展示为一个数据库中的VARCHAR类型的字段,它仍是页面中可选的字段,就像在管理工具中看到的那样。
Once you’ve added that blank=True
, reload the “Add author” edit form (http://127.0.0.1:8000/admin/books/author/add/
), and you’ll notice the field’s label – “Email” – is no longer bolded. This signifies it’s not a required field. You can now add authors without needing to provide e-mail addresses; you won’t get the loud red “This field is required” message anymore, if the field is submitted empty.
一旦你添加了 blank=True,从新加载"Add author" 编辑表单(http://192.168.171.128:8888/admin/books/author/add/),你将会看到 email 字段名称不是加粗的。这代表这个字段不是必填的,当你保存author表单时,即便email为空,也不会出现错误提示信息。