Django-admin链接列问题



在这个答案之后,我想在我的管理页面添加一个链接列,

class AnswerAdmin(admin.ModelAdmin):
    list_display = ('__str__', 'link_to_question', 'time_created', 'time_updated', 'created_by', 'down_vote', 'up_vote')
    def link_to_question(self, obj):
        link = urlresolvers.reverse("admin:QnA_question_change",
                                    args=[obj.question.id])  # model name has to be lowercase
        text = obj.question.__str__
        str = format_html("{}", text)
        return mark_safe(u'<a href="%s">%s</a>' % (link, str))
    class Meta:
        model = Answer

但我得到的回报是:

<bound method Entry.__str__ of <Question: This is a question about technology?>>

我只想要"这是一个问题......"部分显示在我的管理员中。

旁注:当我使用类似 obj.question.text 而不是函数时,它会顺利运行。

目前尚不清楚为什么使用format_html然后将结果传递给mark_safe。您应该能够一步到位 format_html .这具有转义text的优点,以防用户插入恶意内容。

    link = urlresolvers.reverse(...)
    text = obj.question
    link_str = format_html('<a href="{}">{}</a>', link, text)

要调用 __str__ 方法,您需要使用 obj.question.__str__() 调用它。但是,调用str(obj.question)比调用obj.question.__str__()更pythonic。在这种情况下,我认为您根本不需要使用str(),因为您正在使用format_html.

只需设置方法的 allow_tags = True 属性。

class AnswerAdmin(admin.ModelAdmin):
    list_display = ('__str__', 'link_to_question', 'time_created',    'time_updated', 'created_by', 'down_vote', 'up_vote')
    def link_to_question(self, obj):
        link = urlresolvers.reverse("admin:QnA_question_change",
                                args=[obj.question.id])  # model name has to be lowercase
        return u'<a href="{0}">{1}</a>'.format(link, obj.question)
    link_to_question.short_description = u'Link'
    link_to_question.allow_tags = True

最新更新