Customize the styles of Django ClearableFileInput widget

后端 未结 1 1711
野趣味
野趣味 2020-12-21 10:52

I have use ImageField in my django model to have the image upload facility. ImageField uses the ClearableFileInput widget but it does

相关标签:
1条回答
  • 2020-12-21 11:46

    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()
    
    0 讨论(0)
提交回复
热议问题