【问题标题】:django crispy forms overriding layout objects templates ignoreddjango 脆皮表单覆盖布局对象模板被忽略
【发布时间】:2019-04-24 01:20:41
【问题描述】:

我申请了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> 

【问题讨论】:

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


    【解决方案1】:

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

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

    成功设置单个字段模板,但as_crispy_field 不在乎,而是采用表单模板值。

    如果我以表单形式呈现,它会完美运行。

    {% crispy form %}
    

    【讨论】:

      猜你喜欢
      • 2021-02-16
      • 1970-01-01
      • 1970-01-01
      • 2020-08-21
      • 2020-12-01
      • 2014-02-28
      • 1970-01-01
      • 2017-07-22
      • 2019-07-27
      相关资源
      最近更新 更多