django - Django 中模板渲染时出错

标签 django

我正在尝试将此表单提交到我的 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/

相关文章:

python - 新版本的 Django 中 DateModifierNode 的替代品是什么

具有未知数量的复选框字段和多个操作的 Django 表单

python - Django 如何知道在 urls.py 中使用什么 'pk' ?

python - 如何使用 Django 文件存储在 API 和 Worker 之间共享文件

django - staticfiles 和 STATIC_URL 与 virrtualenv - django

Django:select_与表相关 vs 表的字段

python - Disqus SSO - 不工作

django - Google Authenticator (Android) + Django 即使在时间同步之后也说无效 token

Django channel 与 Django 集成

Django:如果用户不是 super 用户,则在模板中隐藏按钮