Django管理员自定义AdminURLFieldWidget小部件缺少“浏览”按钮

时间:2018-07-02 13:38:19

标签: django django-forms django-templates django-admin

我正在尝试自定义Django管理员,并且需要创建针对FileField模板中的change_form记录显示的自定义URL。因此,通过谷歌搜索,我发现以下食谱来自here的图像字段的定制。这是我的代码:

class MyAdminURLFieldWidget(URLInput):
    template_name = 'admin/widgets/url.html'

    def __init__(self, attrs=None):
        final_attrs = {'class': 'vURLField'}
        if attrs is not None:
            final_attrs.update(attrs)
        super(MyAdminURLFieldWidget, self).__init__(attrs=final_attrs)


    def get_context(self, name, value, attrs):
        context = super(MyAdminURLFieldWidget, self).get_context(name, value, attrs)
        context['current_label'] = _('Currently:')
        context['change_label'] = _('Change:')                  
        context['widget']['href'] = smart_urlquote('/DownloadView/' + str(value.instance.id) + '/attachment/') if value else ''
        return context


class FilesAdmin(admin.ModelAdmin):
    list_display = ('id', '_animalid', '_filename', '_filedesc', '_ispublic', 'extra_info')
    search_fields = ('subjectid__animalid',)
    list_per_page = 50

    def formfield_for_dbfield(self, db_field, **kwargs):                                
        if db_field.name == 'filename':
            request = kwargs.pop("request", None)
            kwargs['widget'] = MyAdminURLFieldWidget            
            return db_field.formfield(**kwargs)         
        else:
            return super(FilesAdmin, self).formfield_for_dbfield(db_field, **kwargs)

但是,表单显示的字段没有“浏览”按钮:

enter image description here

我想使用默认值:

enter image description here

那么,如何使Browse按钮出现在自定义窗口小部件中?

1 个答案:

答案 0 :(得分:0)

再次向失去的Django社区问好,

在这里,我再次回答自己的问题。问题在于final_attrs必须是final_attrs = {'type': 'file'}

再次欢迎您。