如何在Django管理界面中将空值分配给对象属性?

huangapple go评论72阅读模式
英文:

How to assign an empty value to an object attribute in Django Admin Interface?

问题

I need the winner attribute to be able to equal an empty value. But when I try to assign it an empty value in Django Admin Interface, I get an error:

我需要使winner属性能够等于空值。但是当我尝试在Django管理界面中将其赋值为空值时,我收到了错误:

如何在Django管理界面中将空值分配给对象属性?

How can I solve this problem? Thank you in advance!

如何解决这个问题?提前感谢您!

英文:

I'm designing an eBay-like website. My project has several models, one of which, namely "Listing", represents all existing products:

class Listing(models.Model):
    title = models.CharField(max_length=64)
    description = models.CharField(max_length=512)
    category = models.CharField(max_length=64)
    image_url = models.URLField()
    owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="created_listings")
    is_active = models.BooleanField(default=True)
    winner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="won_listings", null=True)

I need the winner attribute to be able to equal an empty value. But when I try to assign it an empty value in Django Admin Interface, I get an error:

如何在Django管理界面中将空值分配给对象属性?

How can I solve this problem? Thank you in advance!

答案1

得分: 2

你可以使用 blank=True 来使字段非必填:

class Listing(models.Model):
    # ...
    winner = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name="won_listings",
        null=True,
        blank=True,
    )

> 注意: 通常最好使用 settings.AUTH_USER_MODEL 来引用用户模型,而不是直接使用 User 模型。有关更多信息,请参阅文档中的 引用 User 模型 部分

英文:

You use blank=True&nbsp;<sup>[Django-doc]</sup> to make the field non-required:

<pre><code>class Listing(models.Model):
# &hellip;
winner = models.ForeignKey(
User,
on_delete=models.CASCADE,
related_name=&quot;won_listings&quot;,
null=True,
<b>blank=True</b>,
)</code></pre>


> Note: It is normally better to make use of the settings.AUTH_USER_MODEL&nbsp;<sup>[Django-doc]</sup> to refer to the user model, than to use the User model&nbsp;<sup>[Django-doc]</sup> directly. For more information you can see the referencing the User model section of the documentation.

huangapple
  • 本文由 发表于 2023年6月12日 20:41:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76456775.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定