Reputation: 827
I'm trying to href to my model instances that take a 'model_slug' and 'category_slug' argument. It's giving me NoReverseMatch
html
{% for model in models %}
<a class="btn btn-outline" href="{% url 'main:model_detail_view' model.category_slug model.model_slug %}">View Model</a>
{% endfor %}
views.py
def model_detail_view(request, category_slug, model_slug):
model = Model.objects.get(category__category_slug=category_slug, model_slug=model_slug)
context = {
"models": model,
}
return render(request=request, template_name='main/model_detail.html', context=context)
urls.py
path("products/<str:category_slug>/<str:model_slug>/", views.model_detail_view, name="model_detail_view"),
Upvotes: 1
Views: 237
Reputation: 16032
I think you need category__category_slug
in your template:
<a class="btn btn-outline" href=
"{% url 'main:model_detail_view' model.category.category_slug model.model_slug %}">
View Model</a>
Since you are filtering model
by its fk relation to category
in your view.
Upvotes: 2
Reputation: 476614
The slug of the category
(the category_slug
) is stored in an object linked by a category
foreign key. You thus can access it with:
{% url 'main:model_detail_view' model.category.category_slug model.model_slug %}
You probably should use .select_related(..)
here to fetch the related Category
object in your database query, and avoid a second roundtrip to the database:
def model_detail_view(request, category_slug, model_slug):
model = Model.objects.select_related(
'category'
).get(category__category_slug=category_slug, model_slug=model_slug)
context = {
'model': model,
}
return render(request=request, template_name='main/model_detail.html', context=context)
Note that your model
is a single Model
object, so you can not iterate over it like {% for model in models %}
. You thus render the template with a variable named model
without a {% for … %}
loop in the template.
Upvotes: 2