jun*_*mek 1 django django-admin
请帮我。我放弃。我正在尝试向django管理员添加其他字段。我想在那儿插入图像缩略图。这是我的admin.py的一部分:
class SiteAdmin(admin.ModelAdmin):
    list_display = ('is_active', 'name', 'description', 'keywords', 'date')
    fields = ('name', 'url', 'category', 'subcategory', 'category1',
          'subcategory1', 'description',
          'keywords', 'date', 'group', 'email', 'is_active')
    readonly_fields = ('date',)
    list_display_links = ('name',)
    list_filter = ('is_active',)
    actions = [activate_sites, deactivate_sites]
我很想将'image'添加到list_display。图像由thumbalizr生成。我在models.py中有一个方法:
class Site(models.Model):
    category = models.ForeignKey('Category')
    subcategory = ChainedForeignKey(
        'SubCategory',
        chained_field='category',
        chained_model_field='category',
        show_all=False,
        auto_choose=True,
        blank=True, null=True, default=None)
    name = models.CharField(max_length=70, verbose_name="Tytu?")
    description = models.TextField(verbose_name="Opis")
    keywords = MyTextField(max_length=100, verbose_name="S?owa kluczowe")
    date = models.DateTimeField(default=datetime.now, editable=False)
    url = models.URLField()
    is_active = models.BooleanField(default=False)
    category1 = models.ForeignKey('Category', related_name='category',    blank=True, null=True, default=None)
    subcategory1 = ChainedForeignKey(
        'SubCategory',
        chained_field='category1',
        chained_model_field='category',
        related_name='subcategory',
        show_all=False,
        auto_choose=True, blank=True, null=True)
    group = models.CharField(max_length=10, choices=(('podstawowy', 'podstawowy'),
                                                 ('premium', 'premium')), default='podstawowy',
                         help_text="<div id='group'><ul><li>You can add site to 2 <b>categories</b></li></ul></div>")
    email = models.EmailField(help_text='Podaj adres email')
    def get_absolute_url(self):
        return reverse('site', args=[str(self.category.slug),
                                 str(self.subcategory.slug), str(self.id)])
    def get_thumb(self):
        host = urlparse(self.url).hostname
        if host.startswith('www.'):
            host = host[4:]
        thumb = 'https://api.thumbalizr.com/?url=http://' + host + '&width=125'
        return thumb
这是get_thumb()方法。如何将图像拍摄到每个站点并放入django管理页面?我应该在网站模型中添加其他字段吗?我不想将图像存储在服务器上-它们直接来自thumbalizr。
小智 5
您应该在modeladmin类中添加一个方法。然后,您可以将此方法添加到字段列表中。
class SiteAdmin(admin.ModelAdmin):
    list_display = [..., 'thumb']
    ...
    ...
    def thumb(self, obj):
        return "<img src='{}'  width='20' height='20' />".format(obj.get_thumb())
    thumb.allow_tags = True
    thumb.__name__ = 'Thumb'
| 归档时间: | 
 | 
| 查看次数: | 1942 次 | 
| 最近记录: |