mongodb GridFS django FileFiled 默认 widget 只有一个文件上传框显示不了字段内容,重写widget

首先,定位到:FileFiled 默认 widget 源码:mongoadmin包options.py中,如下:

 1 # Defaults for formfield_overrides. ModelAdmin subclasses can change this
 2 # by adding to ModelAdmin.formfield_overrides.
 3 FORMFIELD_FOR_DBFIELD_DEFAULTS = {
 4     DateTimeField: {
 5         'form_class': forms.SplitDateTimeField,
 6         'widget'    : widgets.AdminSplitDateTime
 7         },
 8     URLField     : {'widget': widgets.AdminURLFieldWidget},
 9     IntField     : {'widget': widgets.AdminIntegerFieldWidget},
10     ImageField   : {'widget': widgets.AdminFileWidget},
11     FileField    : {'widget': widgets.AdminFileWidget},
12     }
13 
14 _fieldgenerator = load_field_generator()()
源码摘取

然后,根据注释部分:

# Defaults for formfield_overrides. ModelAdmin subclasses can change this
# by adding to ModelAdmin.formfield_overrides.

重写widget如下:

 1 from django.contrib.admin.widgets import AdminFileWidget
 2 class FileWidget(AdminFileWidget):
 3     """
 4     A FileField Widget that shows its current value if it has one.
 5     """
 6 
 7     def __init__(self, attrs={}):
 8         super(FileWidget, self).__init__(attrs)
 9 
10     def render(self, name, value, attrs=None):
11         output = []
12         output.append(super(FileWidget, self).render(name, value, attrs))
13         output.append('<p class="help"><textarea name="%s" id="id_%s" rows="10" cols="40" class="vLargeTextField"> %s </textarea></p>' % (name, name, value.read()))
14         return mark_safe(u''.join(output))
MyFileWidget

引入widget如下:

 1 from mongoengine import Document
 2 class AbstractDocument(Document):
 3 
 4     ModelAdmin.formfield_overrides = {
 5         FileField: {'widget': FileWidget},
 6     }
 7 
 8     meta = {
 9         'abstract': True,
10     }
MyDocument

 

posted on 2018-06-20 12:15  王健男  阅读(476)  评论(0编辑  收藏  举报