【问题标题】:Customize the styles of Django ClearableFileInput widget自定义 Django ClearableFileInput 小部件的样式
【发布时间】:2013-11-15 11:10:07
【问题描述】:

我在我的 django 模型中使用了ImageField 来提供图像上传功能。 ImageField 使用 ClearableFileInput 小部件,但它没有提供我可以使用 CSS 自定义的格式良好的 html 标记。下面显示的是由ClearableFileInput 呈现的html 标记。

<div class="form-group" id="div_id">
    <label class="control-label " for="id_image">
        Guide
    </label>

    <div class="controls ">
        Currently:
        <a href="/media/ide.png">de.png</a>
        <input type="checkbox" name="image_" id="image_">
        <label for="image_te">
            Clear
        </label><br>
        Change:
        <input type="file" name="image_te" id="id_i" class="clearablefileinput">
    </div>
</div>

我想做的只是将自定义 css 类添加到这些元素并根据需要更改顺序。如果有人可以建议我解决这个问题,那就太好了。

【问题讨论】:

    标签: python css django django-models django-widget


    【解决方案1】:

    只需创建自己的 Input 类并将渲染可调用更改为您想要的任何内容。例如,这是我制作的一个小头像。它又快又脏,因为它不是 DRY,但它有一个目的:

    class AvatarInput(ClearableFileInput):
    '''renders the input file as an avatar image, and removes the 'currently' html'''
    
    template_with_initial = u'%(initial)s %(clear_template)s<br />%(input_text)s: %(input)s'
    
    def render(self, name, value, attrs=None):
        substitutions = {
            'input_text': self.input_text,
            'clear_template': '',
            'clear_checkbox_label': self.clear_checkbox_label,
        }
        template = u'%(input)s'
        substitutions['input'] = super(AvatarInput, self).render(name, value, attrs)
    
        if value and hasattr(value, "url"):
            template = self.template_with_initial
            substitutions['initial'] = (u'<img src="%s" width="60" height="60"></img>'
                                        % (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)
    

    然后把它放到你的表单类 Meta 中:

        class Meta:
            model = <your model>
            widgets = {'your-field-name': AvatarInput()
    

    【讨论】: