How to override the str method when rendering StackedInline field?

断了今生、忘了曾经 提交于 2020-04-30 07:51:01

问题


I have a many to many relationship:

class GroupeCategoriesCategorie(models.Model):
    groupe_categories = models.ForeignKey(GroupeCategories,
                                          related_name='groupe',
                                          verbose_name=_(u'Groupe'))
    categorie = models.ForeignKey(Categorie,
                                  related_name='categorie',
                                  verbose_name=_(u'Catégorie'))

    def __str__(self):
        return _(u'{} / {}').format(self.groupe_categories, self.categorie)

I always need a representation like the __str__ method before except when rendering in the admin. Why? My admin.py looks like that:

class GroupeCategoriesCategoriesInline(CollapsedStackedInline):
    model = GroupeCategories.liens.through
    fk_name = 'groupe_categories'
    raw_id_fields = ('categorie',)
    extra = 0    

class GroupeCategoriesAdmin(admin.ModelAdmin):

    fields = ('description', 'exemple',)
    inlines = (GroupeCategoriesCategoriesInline,)

And here's the result:

As you can see, when you edit a GroupeCategories, you see the Description field first, and this description is repeated for each manytomany row just after... this is ugly. I'd like to override the __str__ method, but only here. How do you do that?


回答1:


You can easily override the template used by the inline:

class GroupeCategoriesCategoriesInline(admin.StackedInline):
    [...]
    template = 'yourapp/admin/stackedinline.html'

Get a copy of this template:

https://github.com/django/django/blob/master/django/contrib/admin/templates/admin/edit_inline/stacked.html



来源:https://stackoverflow.com/questions/34583077/how-to-override-the-str-method-when-rendering-stackedinline-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!