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!
You use blank=True
[Django-doc] to make the field non-required:
class Listing(models.Model):
# …
winner = models.ForeignKey(
User,
on_delete=models.CASCADE,
related_name="won_listings",
null=True,
blank=True,
)
Note: It is normally better to make use of the
settings.AUTH_USER_MODEL
[Django-doc] to refer to the user model, than to use theUser
model [Django-doc] directly. For more information you can see the referencing theUser
model section of the documentation.