英文:
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管理界面中将其赋值为空值时,我收到了错误:
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:
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
<sup>[Django-doc]</sup> to make the field non-required:
<pre><code>class Listing(models.Model):
# …
winner = models.ForeignKey(
User,
on_delete=models.CASCADE,
related_name="won_listings",
null=True,
<b>blank=True</b>,
)</code></pre>
> Note: It is normally better to make use of the settings.AUTH_USER_MODEL
<sup>[Django-doc]</sup> to refer to the user model, than to use the User
model <sup>[Django-doc]</sup> directly. For more information you can see the referencing the User
model section of the documentation.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论