Django: How can I pass a variable into the url from an anchor tag?

2.3k views Asked by At

Django again... I have seen only one way to do this but I am getting an error.

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.

{% 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? 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):

Reverse for 'wish_item' with keyword arguments '{u'id': 1}' not found. 1 pattern(s) tried: ['wish_item']
1

There are 1 answers

0
spectras On BEST ANSWER

It's getting longer than comments allow, so:

  1. The argument is part of the path, not a query param: {% url 'wish_item' id=x.id %}

  2. 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:

    (?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.