【问题标题】:values show up correctly in view, but not template值在视图中正确显示,但不是模板
【发布时间】:2023-03-16 02:40:02
【问题描述】:

我有以下视图,它在打印报告详细信息中正确显示:

def profile(request):
    owner = User.objects.get (formattedusername='request.user.formattedusername')
    reportdetail = QVReportAccess.objects.filter(ntname = owner.formattedusername).values('report_name')

    print(reportdetail)
    args = {'user':owner, 'applicationaccess':reportdetail}

    return render(request, 'accounts/profile.html', args)

但是,它没有正确传递给我的模板。我是 Django 新手,所以我假设我的模板部分传递报告名称有问题。

      <h2>Current Access Application List</h2>
      <ul>
{{reportdetail.report_name}}
        <li>Application Name: {% for app in reportdetail %}
             <input type="checkbox" name="report_name" value="{{ app.report_name }}" /> {{ reportdetail.report_name }}<br />
        {% endfor %}
        </li>

      </ul>

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    在你看来,

    args = {'user':owner, 'applicationaccess':reportdetail}
    

    与模板中的循环不匹配

    {{ reportdetail.report_name }}
    {% for app in reportdetail %}
    

    您应该将视图更改为:

    args = {'user':owner, 'reportdetail':reportdetail}
    

    或更改模板以使用applicationaccess

    【讨论】:

    • 感谢您的快速响应 Alasdair,因为我理解 'name':name 的第一部分和第二部分有什么区别。
    • {'name':name} 是一个令人困惑的例子,因为你在重复 name。请考虑使用{'name': 'Nick'}。关键是'name',所以当你在模板中使用{{ name }}时,你会得到'Nick'的值。
    • 在调用模板中的键时,如何从值中删除查询集文本部分?当前访问应用程序列表应用程序名称:
    • 这个问题真的没有意义。由于它是一个查询集,因此您可以循环遍历它,例如{% for app in reportdetail %}{{ app }}{% endfor %},或按索引访问项目,例如{{ reportdetail.0 }}.
    • 在模板中打印reportdetail 或包含{{ reportdetail }} 是没有意义的。这是一个查询集,所以正如我所说的,你应该遍历它。也许您希望查询集包含单个项目。在这种情况下,您应该使用get()(它返回一个对象)而不是filter(),它返回一个查询集。
    猜你喜欢
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 2011-09-24
    • 2018-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多