Search code examples
pythondjangomodel

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


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:

enter image description here

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


Solution

  • 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 the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.