Django: Passing model object values through url
I'm having problems wit开发者_开发百科h 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.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>
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?
精彩评论