问题描述
我使用 ImageField
在我的django模型有图像上传设施。 ImageField
使用 ClearableFileInput
小部件,但它不提供格式良好的html标记,我可以使用CSS自定义。显示的是由 ClearableFileInput
呈现的html标记。
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>
我想要做的就是添加自定义CSS类到这些元素,想。如果有人可以向我建议一个解决方案,这将是真的很大。
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.
推荐答案
只需创建自己的Input类,并将render callable改为任何你想要的。例如,这里有一个我添加了一个小化身。它很快又脏,因为它不干,但它的目的:
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)
然后把它放到你的窗体类Meta中:
Then just drop it into your form class Meta:
class Meta:
model = <your model>
widgets = {'your-field-name': AvatarInput()
这篇关于自定义Django ClearableFileInput窗口小部件的样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!