Z
Z
zigen2016-01-06 13:03:24
Django
zigen, 2016-01-06 13:03:24

How to add a custom field to the Django admin?

Good afternoon. Let's say there are two models:
Comment

сlass Comment(models.Model):
    content_type = models.ForeignKey(ContentType, null=True)
    object_id = models.PositiveIntegerField(null=True)
    content_object = GenericForeignKey('content_type', 'object_id')

Well, the news itself:
class News(models.Model):
    title = models.CharField(max_length=250)
    comments = GenericRelation(Comment, related_query_name='news')

I'm trying to figure out how to make it so that in the admin panel, when viewing a comment instance, news.title is displayed instead of the object_id showing news.pk. In short, the headline of the news to which the comment was written. Poke where to look? Add a method for
class CommentAdmin(admin.ModelAdmin)
?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
sim3x, 2016-01-06
@sim3x

class FooTheModel(Model):
    title = models.CharField(max_length=250)
    # blah

    def __str__(self):
         return "{} blah-blah".format(self.title)

A
Alexander, 2016-01-06
@syschel

ModelAdmin.list_display

class CommentAdmin(admin.ModelAdmin):
    list_display = ('news__title')

or its function
class CommentAdmin(admin.ModelAdmin):
    list_display = ('news_title_fnc')

    def news_title_fnc(self, obj):
        return obj.news.title

A
Artem Klimenko, 2016-01-06
@aklim007

https://docs.djangoproject.com/en/1.9/ref/contrib/...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question