【问题标题】:Getting the Name of the Model in a Django template using the Form tag使用 Form 标签在 Django 模板中获取模型的名称
【发布时间】:2016-07-16 17:56:10
【问题描述】:

我想在 Django 的通用表单模板中显示模型的名称。 我考虑过通过表单模板标签访问名称。我知道我可以通过上下文字典轻松地交出这些信息 - 但我想使用来自表单类的信息,因为我已经在 ModelForm 的元数据中提供了信息。

有没有办法在模板中访问这些信息?

更新:

由于我无法直接访问该值,因此我在 views.py 中为表单指定了一个名称:

def form_view(request):
    form = Form(request.POST or None)
    form.name = 'Name'
    ...
    render (request, 'generic_form_tempalte.html', {'form':form}

在模板中:

{% extends '__base.html' %}
<h1 class="page-header">{{form.name}}</h1>
...

这行得通——但它又多了一步

【问题讨论】:

    标签: django forms django-templates


    【解决方案1】:

    不是真的。该模型可通过form._meta.model 获得,但遗憾的是,您无法访问模板中的下划线前缀属性。

    【讨论】:

    • 好吧——还有很多其他的选择,但我希望我可以只写一次;)
    猜你喜欢
    • 2012-01-04
    • 1970-01-01
    • 1970-01-01
    • 2018-03-10
    • 2014-03-20
    • 1970-01-01
    • 2011-03-10
    • 1970-01-01
    • 2013-06-26
    相关资源
    最近更新 更多