Kev
Kev

Reputation: 385

How to display table with group same values in the column on Django Admin

I have a Comment table on Django Admin:

enter image description here

models.py

class Comment(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    item = models.ForeignKey(Listing, on_delete=models.CASCADE)
    comment = models.TextField(max_length=250)
    datetime = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.item}"

admin.py

class CommentInline(admin.TabularInline):
    model = Comment

class ItemAdmin(admin.ModelAdmin):
    inlines = [
        CommentInline,
    ]

@admin.register(Comment)
class CommentAdmin(admin.ModelAdmin):
    list_display = ('item','user','comment','datetime',)
    list_filter = ('item',)

And I want to edit this table with the same values item that will display with a single row, and then after clicked on it will display another table contain user comment and datetime .

Thanks so much for any advice to me !!!

Upvotes: 1

Views: 895

Answers (1)

AMG
AMG

Reputation: 1646

If item is a foreign key to one of your other models, you should be able to use an InlineModelAdmin object to create a tabular inline view of the user/comment/datetime using the item's admin view.

See https://docs.djangoproject.com/en/3.1/ref/contrib/admin/#inlinemodeladmin-objects for reference.

In your case you may end up with something like:

class CommentInline(admin.TabularInline):
    model = Comment
    fields = ('user', 'comment', 'datetime')

class ItemAdmin(admin.ModelAdmin):
    inlines = [
        CommentInline,
    ]

If item is a models.CharField though I don't think you can do it with the Django Admin as provided by Django.

Upvotes: 2

Related Questions