我正在尝试将此表单提交到我的 View :
在 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'),
我收到以下错误:
Exception Type: NoReverseMatch Exception Value: Reverse for 'pcq_list' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['maps/pcq/list/(\d+)/$']
Error during template rendering
In template E:\SampleSite\templates\maps\pcq\pcq_select.html, error at line 1
但是,当我将操作网址中的 product_id 替换为数字时(示例 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
,因为模板不知道此变量。
关于django - Django 中模板渲染时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22949502/