Reputation: 3289
I have been banging my head against the wall for hours on this and its probably incredibly simple.
I need to generate two url slugs from one model. One is actually called slug and is a SlugField which is for the Product title, and the other is a category which is a ForeignKey.
Ideally what I would like to have is
url(r'^products/(?P<category>[^\.]+)/(?P<slug>[^\.]+)/$', tool_detail, name='tool_detail'),
But, the category part of the URL keeps giving generating an "invalid literal for int(), with base 10: 'category' - well, this is one of the errors, I tried many different combinations.
Model
...
slug = models.SlugField()
category = models.ForeignKey(Category)
...
View
def tool_detail(request, slug):
tool = get_object_or_404(Tool, slug=slug)
part = get_object_or_404(Part)
return render(request, 'tool_detail.html', {'tool': tool, 'part': part})
Template
<a href="{% url 'tool_detail' t.category slug=t.slug %}" ... </a>
URL
url(r'^products/tools/(?P<slug>[^\.]+)/$', tool_detail, name='tool_detail'),
Ugh...see how /tools/ is hardcoded?
Thank you for your help.
Upvotes: 0
Views: 1938
Reputation: 808
URL
# query by primary key.
url(r'^products/(?P<category>[0-9]+)/(?P<slug>[^\.]+)/$', tool_detail, name='tool_detail'),
# query by the name.
url(r'^products/(?P<category>[\w]+)/(?P<slug>[^\.]+)/$', tool_detail, name='tool_detail'),
View
def tool_detail(request, **kwargs):
tool = get_object_or_404(Tool, slug=kwargs.get('slug'))
part = get_object_or_404(Part)
return render(request, 'tool_detail.html', {'tool': tool, 'part': part})
Should work it isn't tested.
Upvotes: 2
Reputation: 1320
In url only pass on parameter slug, but on url tag you pass two paramter. Only modify like as Templates
<a href="{% url 'tool_detail' t.slug %}" ... </a>
If slug is int we can change url
url(r'^products/tools/(?P<slug>[0-9]+)/$', tool_detail, name='tool_detail'),
Some example about how to pass dynamic parameter on url tag https://docs.djangoproject.com/en/1.9/intro/tutorial04/
Upvotes: 1