【问题标题】:Error during template rendering in Django在 Django 中的模板渲染期间出错
【发布时间】:2014-05-21 21:14:28
【问题描述】:

我正在尝试将此表单提交给我的视图:

在 pcq_select.html 中

<form action="{% url 'pcq_list' product_id %}" method="POST">{% csrf_token %}
<label>Select the Product:
<select name="product_id">
    {% for entry in products %}
        <option value="{{ entry.id }}">{{ entry.productname }}</option>
    {% endfor %}
</select>
<input type="submit" value="Go"></label>
</form>

在views.py中

def pcq_select(request, template_name='maps/pcq/pcq_select.html'):
    product = Product.objects.all()
    return render(request, template_name, {'products': product})


def pcq_list(request, product_id="1"):
    pcq = Pcq.objects.filter(product_id=product_id)
    data = {}
    data['object_list'] = pcq
    return render(request, 'maps/pcq/pcq_list.html', data)

在 urls.py 中

url(r'^pcq/list/(\d+)/$', views.pcq_list, name='pcq_list'),

我收到以下错误:

异常类型:NoReverseMatch 异常值:“pcq_list”的反向参数“(”,)”和关键字参数“{}”未找到。尝试了 1 种模式:['maps/pcq/list/(\d+)/$']

模板渲染时出错

在模板 E:\SampleSite\templates\maps\pcq\pcq_select.html 中,第 1 行出错

但是,当我用数字替换操作 url 中的 product_id 时(示例 1),整个事情都很好。请帮忙。

【问题讨论】:

    标签: django


    【解决方案1】:

    正确的语法是这样的:

    {% for p in products %} <!-- Let's assume there are several products ... -->
        ...
        <form action="{% url 'pcq_list' product_id=p.pk %}" method="POST">{% csrf_token %}
        ...
    {% endfor %}
    

    然后,你必须在你的 urls.py 中指定 url 以这种方式等待一个 id:

    url(r'^pcq/list/(?P<product_id>\d+)$', views.pcq_list, name='pcq_list')
    

    你不能按原样写product_id,因为模板不知道这个变量。

    【讨论】:

    • 不错。你的代码是我所期望的。你试过我写的解决方案了吗?
    • 我用for标签附上了完整的表格。将条目替换为 p。我收到与我发布的相同的错误消息。
    • 我猜这是因为 urls.py 必须指定 ID(请参阅我更新的帖子)
    • 是的! Url 更改和 product_id=p.pk 解决了这个问题。非常感谢大卫!
    • 谢谢,我已经被类似的问题困扰了 2 天,我正在关注 django 教程,其中 question.id 在表单操作中传递,其值可用于表单。在我的情况下,值不能直接获得,因此它给了我渲染错误。现在我已经提取了值并轻松传递到下一个 html 页面,谢谢
    【解决方案2】:

    您没有显示您的视图,但看起来您没有将任何名为 product_id 的内容传递给模板。

    【讨论】:

      【解决方案3】:

      您是否将产品传递给模板?如果是这样,请将您原来的product_id 更改为product.id

      即:

      <form action="{% url 'pcq_list' product.id %}" method="POST">{% csrf_token %}
      

      【讨论】:

      • 我试过但收到一条错误消息:无法解析剩余部分:'{{' from '{{'
      • 你能发布你的views.py吗?
      • 我已经添加了views.py
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-31
      • 2017-05-21
      • 2017-07-03
      • 2017-11-13
      • 2020-08-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多