在管理员列表视图上显示Django自定义字段

时间:2019-10-21 12:52:32

标签: python django listview django-custom-field

我正在为我的项目使用django-taggit-labels。我试图使这些标签可从管理员列表视图访问。我正在从这里使用示例:Custom list_editable field in django admin change list, which doesn't correspond directly to a model field。基本上,我试图覆盖get_changelist_form方法并显示我的自定义字段(djago-taggit-labels)

我得到的错误是我没有得到管理员列表上的小部件:

 taggit.forms.TagField object at 0x7f83a2cae9d0

但不是实际的标签。

有人知道如何显示实际标签而不是对象吗?

admin.py

class YoutubeVideoAdmin(admin.ModelAdmin):
    form = YoutubeTagLabel
    model = YoutubeVideo
    list_display = (
        'admin_thumbnail', 
        'user',
        'title',
        'admin_url',
        'published_at',
        'description',
        # Categories are the tags.
        'categories'
     )

    list_filter = (
        ('user__user', admin.RelatedOnlyFieldListFilter),
        'published_at',
        ('tags', custom_titled_filter('Category')),
    )
    ordering = ('-published_at', )
    search_fields = ('title', 'description', 'tags__name', )

    readonly_fields = ('time_created',
                       'time_modified',
                       'user',)

    def get_changelist_form(self, request, **kwargs):
        return YoutubeTagLabelForm

    def admin_thumbnail(self, obj):
        if obj.thumbnail_url:
            return mark_safe('<img src="%s" height = "60"/>' % 
            obj.thumbnail_url)
        else:
            return None

    def admin_url(self, obj):

        return mark_safe(f'<a href={obj.url} target="_blank"> 
   {obj.url}</a>')

    def get_queryset(self, request):
        return super().get_queryset(request).prefetch_related('tags')

    # def categories populate tags

    def categories(self, obj):
        return u", ".join(o.name for o in obj.tags.all())

forms.py

class YoutubeTagLabelsWidget(LabelWidget):
    tags = TagField(required=False, widget=LabelWidget)


class YoutubeTagLabelForm(forms.ModelForm):
    tags = TagField(required=False, widget=YoutubeTagLabelsWidget)

def __init__(self, *args, **kwargs):
    instance = kwargs.get('instance')
    if instance:
        initial = kwargs.get('initial', {})
        initial['description'] = TagField(required=False, widget=YoutubeTagLabelsWidget)
        kwargs['initial'] = initial
    super(YoutubeTagLabelForm, self).__init__(*args, **kwargs)

models.py

class YoutubeVideo(TimeStampedModel):
    user = models.ForeignKey(YoutubeUser, on_delete=models.CASCADE)
    title = models.TextField()
    url = models.URLField()
    published_at = models.DateTimeField()
    description = models.TextField(null=True)
    thumbnail_url = models.URLField()
    video_id = models.TextField(max_length=20)
    tags = TaggableManager()

0 个答案:

没有答案