A
A
avigmati2015-01-18 22:14:54
Django
avigmati, 2015-01-18 22:14:54

How to override object names in forms.ModelMultipleChoiceField in Django Admin?

Models:

class PostTag(models.Model):
    title = models.CharField(max_length=255)

class Post(models.Model):
    title = models.CharField(max_length=255)
    post_tag = models.ManyToManyField(PostTag, null=True, blank=True)

Admin:
class PostAdmin(ModelAdmin):
    filter_horizontal = ('post_tag',)

A list of tags is displayed, but I need to add the number of posts for this tag to the tag name. How to do this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya, 2015-01-18
@FireGM

https://docs.djangoproject.com/en/1.7/ref/contrib/...
there are many examples there. In short, you create a new function for the model that returns the amount. Add allow_tags. We go to the admin panel and write lists_display. Everything.
True, I did not use manytomany. For foreign keys only.
I decided to check, everything is working fine. Only not quite the same, but the principle is clear.
models.py

from django.utils.html import format_html

class PostTag(models.Model):
    title = models.CharField(max_length=255)

    def __str__(self):
        return self.title

    def get_count_posts(self):
        return format_html('<span style="color: red">{0}</span>', self.post_set.count())

    get_count_posts.allow_tags = True

class Post(models.Model):
    title = models.CharField(max_length=255)
    post_tag = models.ManyToManyField(PostTag, null=True, blank=True)

    def __str__(self):
        return self.title

admin.py
from games.models import PostTag, Post


class PostTagAdmin(admin.ModelAdmin):
    list_display = ('title', 'get_count_posts')


admin.site.register(PostTag, PostTagAdmin)
admin.site.register(Post)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question