設置字段可選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爲空,也不會出現錯誤提示信息。