1

Not quite sure how to accomplish this.

I have a Post model which references a foreign key to the Category model.

class Post(models.Model):

    STATUS_CHOICES = (
        ('draft', 'Draft'),
        ('published', 'Published'),
    )

    title = models.CharField(max_length=250)
    slug = models.SlugField(max_length=250, unique_for_date='publish')
    author = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='feature_posts')
    body = models.TextField("Body")
    lead_in = models.CharField("Lead In", max_length=500, default='', blank=True)
    is_featured = models.BooleanField("Is Featured?", default=False)
    likes = models.IntegerField(default=0, blank=True)
    views = models.IntegerField(default=0, blank=True)
    category = models.ForeignKey('Category', null=True, blank=True)

class Category(models.Model):

    name = models.CharField(max_length=200)
    slug = models.SlugField()
    parent = models.ForeignKey('self',blank=True, null=True ,related_name='children')

    class Meta:
        unique_together = ('slug', 'parent',)
        verbose_name_plural = "categories"

All works as intended pretty nicely, except for this in the admin dashboard:

enter image description here

Can anyone give me the pro-tip to avoid this...? It's probably line 1 of the Django admin handbook but I can't for the life of me find line 1! :D

Looked through Django 1.11 admin documentation in models, foreignkey fields, admin etc etc but to no luck.

N.B. It might be worth noting that I am using wagtail, if there are any subtle differences

GCien
  • 2,221
  • 6
  • 30
  • 56

1 Answers1

5

If you are OK with changing the representation of the category in other places:

class Category(models.Model):
    # ...
    def __str__(self):  # what will be displayed in the admin
        return self.name

Otherwise use the solution described in Django admin - change ForeignKey display text.

dukebody
  • 7,025
  • 3
  • 36
  • 61
  • Works like a treat. I've seen this __str__(self) function used, but was only sure this applied to the model itself in the admin. Learning from this was ideal! Thank you. – GCien Jan 29 '18 at 22:44