【问题标题】:In Django for loop in html template is not working correctly在 Django 中,html 模板中的 for 循环无法正常工作
【发布时间】:2020-08-24 11:29:42
【问题描述】:

我想要下拉菜单中的报告名称,但我无法从字典中获取项目 views.py

def add(request):
    report_item = {}
    if request.method == "POST":
        src=request.POST['src']
        width=request.POST['width']
        height=request.POST['height']
        name=request.POST['name']
        report_item = {'src':src, 'width':width, 'height':height, 'name':name}
        #template = loader.get_template('report_one.html')
        #context={'report_item':report_item}
        return render(request, 'report_one.html', report_item)
    else:
        return render(request, 'report_one.html', report_item)

index.html

li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Reports<span class="caret"></span></a>
<ul class="dropdown-menu">
    <li class="dropdown-header">Reports</li>
    <li>
        <div class="buttons pull-right">
            <a href="{% url 'report:reporttest' %}" class="btn btn-xs btn-success" title="Add"><i class="fa fa-plus"></i></a>
        </div>
        <a href="{% url 'report:reporttwo' %}">Report one</a>
    </li>
    {% for key, value in report_item.items %}
<li>
    <a href="{% url 'report:add' %}">{{ value.name }}</a>
</li>
{% endfor %}
</ul>

我想在下拉菜单中动态添加报表名称

我已成功创建报告,并且报告名称也显示在下拉列表中,但问题是当我单击报告名称时,报告名称将从下拉列表中删除

【问题讨论】:

    标签: django


    【解决方案1】:

    这是我会尝试的:

    <li>
        <a href="{% url 'report:add' %}">{{ name }}</a>
    </li>
    

    【讨论】:

    • 我已经更新了我的答案,只需调用 dict ass 的键如下:{{ name }}
    • 我已经使用了这个 {{ name }} 代码...但是我遇到了问题...当我在下拉列表中单击此报告名称时,报告的名称将从dropdown ...我希望所有报告名称都显示在下拉菜单中
    • 您能否在模板中提供您想要的预期输出?
    • 每个报告都保留在一个模型上?
    【解决方案2】:

    您传递给模板的上下文数据不包含名为report_item 的值,因此您实际上是在循环一个虚假值。尝试循环遍历None 不会在 Django 的模板语言中引发错误——它什么也不做。

    您要做的是取消注释 #context={'report_item':report_item} 并将其传递给 render 而不是 report_item

    以下是我将如何重构您的视图:

    def add(request):
        report_item = {}
    
        if request.method == "POST":
            report_item.update(
                height=request.POST["height"],
                name=request.POST["name"],
                src=request.POST["src"],
                width=request.POST["width"],
            )
    
        context = {"report_item": report_item}
        return render(request, "report_one.html", context)
    

    【讨论】:

    • 同样的问题没有获取数据 src width height 有空白值
    • 它只对 POST 请求有价值。如果您只是使用 GET 请求,它仍然是一个空白值。你有仔细检查过吗?
    • 你能看到这个帖子吗stackoverflow.com/q/63551372/13755750 实际上我想在我的项目中完成这一切,但到目前为止我还没有得到任何解决方案
    猜你喜欢
    • 2012-01-02
    • 2013-03-31
    • 2013-06-26
    • 2020-10-27
    • 1970-01-01
    • 2017-11-11
    • 1970-01-01
    • 1970-01-01
    • 2016-01-01
    相关资源
    最近更新 更多