【问题标题】:How to override template_name in SelectDateWidget (Django 1.11)如何在 SelectDateWidget (Django 1.11) 中覆盖 template_name
【发布时间】:2017-10-04 22:17:05
【问题描述】:

我需要将字段包装在 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 中不起作用。 我试图覆盖'django/forms/widgets/select_date.html':

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

但 Django 包含“django/forms/widgets/select_date.html”而不是我的模板“accounts/templates/accounts/custom_select_date.html”。不显示任何错误消息。

【问题讨论】:

    标签: django django-templates django-widget


    【解决方案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,
            }
    

    【讨论】:

    • 您也可以在 UserProfileForm:ClearableFileInput.template_name = 'django_overrides/forms/widgets/clearable_file_input.html' 中不创建 CustomClearableFileInputWidget,但这会覆盖当前表单中的所有 ClearableFileInput。
    【解决方案2】:

    在使用父类创建子类时使用 super 覆盖它

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

    【讨论】:

    • 谢谢。我找到了另一种方法来解决这个 SelectDateWidget.template_name = 'accounts/custom_select_date.html'
    • @ctac 请问​​您能用其他方式创建答案吗?您还需要对小部件进行子类化吗?
    猜你喜欢
    • 2018-10-09
    • 1970-01-01
    • 2018-02-01
    • 1970-01-01
    • 2018-02-01
    • 1970-01-01
    • 2020-11-08
    • 2011-11-06
    • 1970-01-01
    相关资源
    最近更新 更多