Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow user-defined display function in enhance #159

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

twang817
Copy link
Contributor

Allow user provided display function, so that we can do something like this:

from django.urls import reverse
from django.utils.html import format_html_join
from tagulous.constants import COMMA, DOUBLE_QUOTE, QUOTE, SPACE


def _my_create_display(field_name):
    def display(self, obj):
        field = getattr(obj, field_name)
        names = []
        for tag in field.tags:
            name = str(tag)
            name = name.replace(QUOTE, DOUBLE_QUOTE)
            if COMMA in name or SPACE in name:
                names.append("%s" % name)
            else:
                names.append(name)
        return format_html_join(
            ", ",
            '<a href="{}">{}</a>',
            (
                (reverse("admin:%s_%s_change" % (
                    field.model._meta.app_label,
                    field.tag_model.__name__.lower()
                ), args=(tag.id,)), name)
                for name, tag in zip(names, field.tags)
            )
        )
    display.short_description = field_name.replace("_", " ")
    return display


class MyModel(models.Model):
    tags = tagulous.models.TagField(blank=True)


class MyAdmin(tagulous.admin.TaggedModelAdmin):
    list_display = ['tags']
tagulous.admin.enhance(MyModel, MyAdmin, display_func=_my_create_display)
admin.site.register(MyModel, MyAdmin)

This produces a nice list of tags in the list_display, where each tag links to the change view of that specific tag in the admin:

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: No status
Development

Successfully merging this pull request may close these issues.

1 participant