M
M
maxclax2015-03-06 13:45:47
Django
maxclax, 2015-03-06 13:45:47

How to remove code repetition in DJANGO?

I have many models, and in the admin panel in each admin.py I prescribe column formatting.

list_display = ('title', 'info_tag_created_at', 'info_tag_updated_at')
    list_filter = ("languages", "is_view")


    def info_tag_updated_at(self, obj):
        if not obj.pk:
            return ''
        return obj.updated_at.strftime("%d.%m.%Y") + "<br/> <sup>" + obj.updated_at.strftime("%H:%M:%S") + "</sup>"

    info_tag_updated_at.short_description = _('news.admin.info_tag_updated_at.short_description')
    info_tag_updated_at.allow_tags = True

    def info_tag_created_at(self, obj):
        if not obj.pk:
            return ''
        return obj.created_at.strftime("%d.%m.%Y") + "<br/> <sup>" + obj.created_at.strftime("%H:%M:%S") + "</sup>"

    info_tag_created_at.short_description = _('news.admin.info_tag_created_at.short_description')
    info_tag_created_at.allow_tags = True

Looking for a solution on how to get around code repetition. For example, in almost every model there are created_at and updated_at fields, respectively, in each admin.py I write the functions written above. In addition to them, there are many others that are repeated. How to bypass it? Maybe you can put it in one file or is there a completely different solution to this problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yuri Shikanov, 2015-03-06
@maxclax

Make your base ModelAdmin and put the common for ALL models there.
Make some mixin classes to add some methods that only some models need.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question