django站点管理——(二)

设置字段可选

  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字段是可选的 - 也就是说,应该允许空白字符串。 在现实世界中,您可能没有每个作者的电子邮件地址。

  

  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:

  要指定email字段是可选的,需编辑Author模型(你将从第4章回忆起,它位于mysite / books / models.py中)。 只需将 blank= True 添加到电子邮件字段,如下所示:

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.

  这告诉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.

  这里有一些有趣的事情,直到现在,除过__str__()方法以外,我们的模型已作为我们数据库表的定义——实质上是用python语法,写CREATE TABLE语句。在添加 blank = True时,我们已经开始扩展我们的模型,而不是简单地定义数据库表的样子。

  

  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.

  现在,我们的模块类开始成为一个富含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为空,也不会出现错误提示信息。

  

  

原文地址:https://www.cnblogs.com/mujinxinian/p/7903433.html