[英]Django: How can I pass a variable into the url from an anchor tag?
Django again... I have seen only one way to do this but I am getting an error. 再次使用Django ...我仅看到一种方法来执行此操作,但出现错误。
I have the url: 我有网址:
url(r'^wish_item/(?P<id>\d#)$', views.wish_item, name="wish_item")
and the view, 和视图,
def wish_item(request, id):
but the anchor tag in my template is causing me a NoReverseMatch. 但模板中的定位标记导致我出现NoReverseMatch。
{% for x in myitems %}
<a href="{% url 'wish_item' %}?id={{x.id}}">{{x.item}}</a>
{% endfor %}
What is the correct way to pass the variable into the url? 将变量传递到url的正确方法是什么? Is anything wrong with the regex in my url or am I writing this wrong in the template tag?
网址中的正则表达式有什么问题吗?还是我在模板标记中写错了? both?
都?
EDIT: changed the template tag to 编辑:将模板标签更改为
<a href="{% url 'wish_item' id=x.id %}">{{x.item}}</a>
but I still get the error (after clearing the url to just /wish_item because the regex gave me an error also): 但是我仍然会收到错误消息(在将URL清除为/ wish_item之后,因为正则表达式也给了我一个错误):
Reverse for 'wish_item' with keyword arguments '{u'id': 1}' not found. 1 pattern(s) tried: ['wish_item']
It's getting longer than comments allow, so: 它的时间超出了注释所允许的时间,因此:
The argument is part of the path, not a query param: {% url 'wish_item' id=x.id %}
参数是路径的一部分,而不是查询参数:
{% url 'wish_item' id=x.id %}
Your regexp is (very likely to be) wrong. 您的正则表达式是(很可能是)错误的。
(?P<id>\\d#)
This accepts exactly one digit followed by exactly one hash sign. 这接受正好一个数字,后跟正好一个哈希符号。 Probably you meant this?
可能你是这个意思吗?
(?P<id>\\d+)
That is, one or more digits? 即一个或多个数字?
For reference, you have the full regex syntax over here . 作为参考,您在此处具有完整的正则表达式语法。 By the way, if you just have a numeric id, I suggest sticking to this:
顺便说一句,如果您只有数字ID,建议您坚持以下操作:
(?P<id>[0-9]+)
The difference is \\d
will also accepts other characters marked as digits in unicode, which you probably won't handle later on. 区别在于
\\d
还将接受unicode中标记为数字的其他字符,您以后可能不会处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.