django 修改model field后台默认的显示方式

我们都知道django模型在后台有默认的显示方式,它的显示是靠widget(不了解widget参考:https://docs.djangoproject.com/en/dev/ref/forms/widgets/)这种方式,所以要修改feild的默认显示方式,需要自定义widget,下面是一个自定义ImageField的widget

django默认的ImageField在后台显示的是image的url,我们更希望看到image的thumbnail,那要怎么做呢:

1、model

class RecommendApp(models.Model):
    slider_image=models.ImageField('幻灯截图',upload_to="slider",null=True,blank=True)

2、在widget.py中自定义imageWidget

#coding=utf8
from django.forms.widgets import ClearableFileInput,CheckboxInput
from django.utils.html import escape, conditional_escape
from django.utils.encoding import StrAndUnicode, force_unicode
from django.utils.safestring import mark_safe

class ImageWidget(ClearableFileInput):
    def render(self, name, value, attrs=None):
        substitutions = {
            'initial_text': self.initial_text,
            'input_text': self.input_text,
            'clear_template': '',
            'clear_checkbox_label': self.clear_checkbox_label,
        }
        template = u'%(input)s'
        substitutions['input'] = super(ClearableFileInput, self).render(name, value, attrs)

        if value and hasattr(value, "url"):
            template = self.template_with_initial
            substitutions['initial'] = (u'<a href="%s" target="_blank"><img width="100px" height="100px" src="%s"></a>'
                                        % (escape(value.url),
                                           escape(value.url)))
            if not self.is_required:
                checkbox_name = self.clear_checkbox_name(name)
                checkbox_id = self.clear_checkbox_id(checkbox_name)
                substitutions['clear_checkbox_name'] = conditional_escape(checkbox_name)
                substitutions['clear_checkbox_id'] = conditional_escape(checkbox_id)
                substitutions['clear'] = CheckboxInput().render(checkbox_name, False, attrs={'id': checkbox_id})
                substitutions['clear_template'] = self.template_with_clear % substitutions

        return mark_safe(template % substitutions)

3、在admin.py中添加自定义widget

class RecommendAppAdmin(admin.ModelAdmin):
    
    def formfield_for_dbfield(self, db_field, **kwargs):
        if db_field.name=='slider_image':
            kwargs['widget']=ImageWidget
            try:
                del kwargs['request']
            except KeyError:
                pass
            return db_field.formfield(**kwargs)
        return super(RecommendAppAdmin, self).formfield_for_dbfield(db_field, **kwargs)
admin.site.register(RecommendApp,RecommendAppAdmin);

通过上面这3步就能在后台看到image的缩略图了

你可能感兴趣的:(django 修改model field后台默认的显示方式)