Search code examples
djangodjango-modelsdjango-admin

model doesn't display title Django


In the admin the content of my model doesn't show a title, now I now that I can make a field called title but then I need it to be an incrementing int, but if I do that Django tells me that that can't happen because it will get rid of the ID, is there anyway I can fix this?

model:

class ReviewRating(models.Model):
    album = models.ForeignKey(albums, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    subject = models.CharField(max_length=100, blank=True)
    review = models.TextField(max_length=500, blank=True)
    rating = models.FloatField()
    ip = models.CharField(max_length=20, blank=True)
    status = models.BooleanField(default=True)
    created_date = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.subject

how the admin looks

if there is any information missing please let me know


Solution

  • You can provide something like that for displaying the ID of your model when subject is empty:

    class ReviewRating(models.Model):
        album = models.ForeignKey(albums, on_delete=models.CASCADE)
        user = models.ForeignKey(User, on_delete=models.CASCADE)
        subject = models.CharField(max_length=100, blank=True)
        review = models.TextField(max_length=500, blank=True)
        rating = models.FloatField()
        ip = models.CharField(max_length=20, blank=True)
        status = models.BooleanField(default=True)
        created_date = models.DateTimeField(auto_now_add=True)
    
        def __str__(self):
            return self.subject or f"ReviewRating #{self.pk}"
    

    You can replace f-string by a translation if you want