在Django中模板渲染期间出错

时间:2014-04-08 22:34:21

标签: django

我正在尝试将此表单提交给我的观点:

在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替换动作URL中的 product_id 时(示例1),整个过程都很有效。请帮助。

3 个答案:

答案 0 :(得分:4)

正确的语法是这样的:

{% 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,因为模板不知道此变量。

答案 1 :(得分:1)

您不会显示自己的观点,但看起来您没有将任何名为product_id的内容传递给模板。

答案 2 :(得分:-1)

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

I.e。:

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