【问题标题】:Django admin link at user model from another in list来自列表中另一个用户模型的 Django 管理链接
【发布时间】:2021-08-01 15:37:57
【问题描述】:

在我的 django 管理员中,我有一个链接到用户的模型,我会在我的列表中创建一个链接,以便直接从连接的模型传递到相关的用户 ID 编辑页面,我这样做:

class a_cards(models.Model):
    CK_CHOICES = (
        ('A', 'Ambassador'),
        ('M', 'Medico'),
        ('P', 'Paziente'),
        ('S', 'Senator'),
    )

    c_num = models.CharField(max_length=200, unique=True,
                         null=True, blank=True, verbose_name="Numero card")
    c_data = models.DateTimeField(auto_now=True)
    c_type = models.CharField(
    max_length=1, choices=CK_CHOICES, verbose_name="Tipo utenza")
    c_email = models.CharField(max_length=200, unique=True,
                         null=True, blank=True, verbose_name="Notifica Email")
    c_agente = models.ForeignKey(AgenteProfile, on_delete=models.CASCADE,
                             null=True, blank=True, related_name="ag_id", verbose_name="Agente")
    c_user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE, verbose_name="Cliente" )

    class Meta:
        verbose_name = 'Cards'
        verbose_name_plural = 'Cards'

    def user_link(self):
        if self.c_user:
            return '<a href="%s">%s</a>' % (reverse("admin:auth_user_change", args=(self.c_user.id,)) , escape(self.c_user))

    user_link.allow_tags = True
    user_link.short_description = "User" 

    def __str__(self):
        return self.c_num

在管理员中:

class cardAdmin(ImportExportModelAdmin):

    list_filter = ('c_type',)
    list_display = ('c_num', 'c_data', 'c_type', 'c_agente', 'user_link',)
    ...

但是当我打开我的管理页面时,我看到了正确的链接,但不是 libk 形式:

错误在哪里? 为什么我没有可点击的链接?

提前非常感谢

【问题讨论】:

    标签: python-3.x django django-admin


    【解决方案1】:

    您应该使用format_html 来构建 HTML 内容。所以重构你的 url 生成器方法,比如;

    class a_cards(models.Model):
        ....
        
        def user_link(self):
            if self.c_user:
                return format_html('<a href="{url}">{text}</a>', url=reverse("admin:auth_user_change", args=(self.c_user.id,)), text=self.c_user)
            return "-"
    
    user_link.short_description = "User"
    user_link.allow_tags = True
    

    来自文档;

    所有 args 和 kwargs 在传递给 str.format() 之前都通过 conditional_escape() 传递。

    因此您无需指定额外的escape()

    【讨论】:

      猜你喜欢
      • 2018-06-17
      • 2014-04-27
      • 2020-09-06
      • 2021-09-22
      • 1970-01-01
      • 2010-11-01
      • 2012-04-20
      • 2021-06-27
      • 2010-10-06
      相关资源
      最近更新 更多