Customize the styles of Django ClearableFileInput

2019-01-28 19:10发布

问题:

I have use ImageField in my django model to have the image upload facility. ImageField uses the ClearableFileInput widget but it does not provide well formatted html markup that i can customize using CSS. Shown bellow is the html markup that rendered by ClearableFileInput.

<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>

Simply what i want to do is to add custom css classes to these elements and change the order as i want. It would be really great if someone can suggest me a solution to this.

回答1:

Just make your own Input class and alter the render callable to whatever you want. As an example, here's one I made to add in a little avatar. It's quick and dirty, in that it's not DRY, but it serves a purpose:

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)

Then just drop it into your form class Meta:

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