django脆皮表单覆盖布局对象模板被忽略

时间:2018-11-21 13:01:57

标签: python django django-templates django-crispy-forms

我申请了this  因此我有

self.helper.layout = Layout(
    Field(
    'title', template="mytemplate.html"
    ) ,

结果是我的模板没有被渲染 在以下代码中, helper.field_template为None

(C:\ myapp \ lib \ crispy_forms \ templatetags \ crispy_forms_filters.py):

@register.filter(name='as_crispy_field')
def as_crispy_field(field, template_pack=TEMPLATE_PACK, label_class="", field_class=""):
    """
    Renders a form field like a django-crispy-forms field::

        {% load crispy_forms_tags %}
        {{ form.field|as_crispy_field }}

    or::

        {{ form.field|as_crispy_field:"bootstrap" }}
    """
    if not isinstance(field, forms.BoundField) and settings.DEBUG:
        raise CrispyError('|as_crispy_field got passed an invalid or inexistent field')

    attributes = {
        'field': field,
        'form_show_errors': True,
        'form_show_labels': True,
        'label_class': label_class,
        'field_class': field_class,
    }
    helper = getattr(field.form, 'helper', None)

    template_path = None
    if helper is not None:
        attributes.update(helper.get_attributes(template_pack))
        template_path = helper.field_template
    if not template_path:
        template_path = '%s/field.html' % template_pack
    template = get_template(template_path)

    c = Context(attributes).flatten()
    return template.render(c)

如果我在调试时将helper.field_name修改为mytemplate.html,我会看到渲染成功。

问题是什么原因导致我的模板被忽略?

重要提示,我的表格扩展了:

class RoomForm(ModelForm)

其中ModelFormhere一样


在我的表单中,我使用:

  {{ form.title | as_crispy_field }}

我观点的相关部分是:

  form = RoomForm(None, prefix="submit-room" )                   
  return render(request, 'edit_room.html', { 'form': form })

最后,将mytemplate.html复制到“任何地方”: C:\myapp\lib\crispy_forms\templates\bootstrap4C:\myapp\templates\mytemplate.html

{% load custom_tags %}
<div>tutu</div>
<div>{{field}}</div> 

1 个答案:

答案 0 :(得分:0)

我不想改变问题的目的,以至于我可以用到目前为止得到的输入来回答它:

self.helper.layout = Layout(
    Field(
    'title', template="mytemplate.html"
    ) 

成功设置了各个字段模板,但是as_crispy_field对此并不在意,而是采用表单模板值。

如果我将其渲染为表单,则效果很好。

{% crispy form %}
相关问题