如何覆盖SelectDateWidget中的template_name(Django 1.11)

时间:2017-05-06 14:44:21

标签: django django-templates django-widget

我需要在div中包装字段。 在Django 1.10中:

class CustomSelectDateWidget (SelectDateWidget):
    def render(self, name, value, attrs=None):
       ...
       output = []
       for field in self._parse_date_fmt():
            if field == 'year':
                output.append('<div class="input-field col s4">' + html['year'] + '</div>')
            elif field == 'month':
                output.append('<div class="input-field col s5">' + html['month'] + '</div>')
            elif field == 'day':
                output.append('<div class="input-field col s3">' + html['day'] + '</div>')
        return mark_safe('\n'.join(output))

它在Django 1.11中无效。 我试图覆盖&#39; django / forms / widgets / select_date.html&#39;:

class CustomDateWidget(SelectDateWidget):
    def get_template_names(self):
        return ['accounts/custom_select_date.html']

但是Django包含&#d; django / forms / widgets / select_date.html&#39;而不是我的模板&#39; accounts / templates / accounts / custom_select_date.html&#39;。没有显示错误消息。

2 个答案:

答案 0 :(得分:1)

使用super来覆盖它,因为您正在使用类父类来创建子类

form = super(CustomSelectDateWidget , self).get_form(form_class)

答案 1 :(得分:1)

所以我找到了一种简单的方法。在我的情况下,我想在ImageField中显示图像。这是代码:

复制django的clearable_file_input.html模板,对其进行自定义并将其保存到,例如django_overrides/forms/widgets/clearable_file_input.html,例如:

{% if is_initial %}{{ initial_text }}: <img src="{{ widget.value.url }}" />{% if not widget.required %}
<input type="checkbox" name="{{ checkbox_name }}" id="{{ checkbox_id }}" />
<label for="{{ checkbox_id }}">{{ clear_checkbox_label }}</label>{% endif %}<br />
{{ input_text }}:{% endif %}
<input type="{{ widget.type }}" name="{{ widget.name }}"{% include "django/forms/widgets/attrs.html" %} />

对原始窗口小部件进行子类化,将template_name设置为新模板:

from django.forms import ClearableFileInput

class CustomClearableFileInputWidget(ClearableFileInput):
    template_name = 'django_overrides/forms/widgets/clearable_file_input.html'

更新您的表单以使用此小部件:

class UserProfileForm(ModelForm):
    class Meta:
        model = UserProfile
        exclude = ['id', 'user']
        widgets = {
            'photo': CustomClearableFileInputWidget,
        }