0

I'm having problems with passing model object values through a URL pattern. The URL:

url(r'^cities/(?P<city>\w+)/$', 'city_firm', name='city_firm'),

In the template (from the index page) I have:

<a href="{% url city_firm city %}">{{ city }}</a>

This is in a for loop.

The related view is:

def city_firm(request, city):
    city1 = Cities.objects.get(city=city)
    cityf = city1.Firms.all()
    return render_to_response('cityfirm.html', {'cityf': cityf})

The two models (Cities, Firms) are in a many to many relationship. I keep getting TemplateSyntaxError at index (NoReverseMatch while rendering: Reverse for 'city_firm' with arguments '(<Cities: >,)' and keyword arguments '{}' not found). In the template link tag I tried: {% url city_firm city=city %}, {% url city_firm city=cities.city %}. Nothing changed. The urlconf part seems right. The problem seems to be in the template. Maybe there is an issue with the string values of the object as they aren't in English. But I took several precautions to prevent this. There is maybe something wrong with the view but the error says template. Any ideas?

Solution:
Thanks everyone! Finally I figured it out. The problem was simple: I was trying to send object attribute names through the url, that had non-English characters and spaces. To fix it, I had to edit my models.

2
  • try to send city.city instead of city Commented Dec 15, 2010 at 7:28
  • If you solved your own issue, supply it as an answer and accept it Commented Apr 23, 2012 at 22:41

2 Answers 2

4

The issue is that you can't pass an object in a URL, you can only pass characters. So you need to put the part of the city object that contains the text you want to be in the URL - in your case, it appears to be an attribute also called city, which is what you use to in the lookup to get the object in the view. So it should be:

<a href="{% url city_firm city.city %}">{{ city }}</a>
Sign up to request clarification or add additional context in comments.

1 Comment

Unfortunately there's indeed noway to pass an object so that the url resolves expected keywords from that object. I can't find any app doing that in Django.
0

I don't think name means what you think it does - remove that and read this: http://docs.djangoproject.com/en/dev/topics/http/urls/#naming-url-patterns

As far as the error... the NoReverseMatch is telling you that it's not seeing any arguments. Remember that nonexisting template variables expand to "". Make sure city is in context when you're running that code - maybe post the for in the template?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.