问题
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