I have a detail view for categories and if i pass in the URL directly it works just fine. But if i want to pass it as a link in my template it gets an error. Here is my models:
class Category(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return (self.name)
def get_absolute_url(self):
return reverse("home")
Here is my views:
class CategoryClassView(TemplateView):
model = Category
template_name = "categories.html"
def get_context_data(self, **kwargs):
cats = kwargs.get("cats")
category_posts = Category.objects.filter(name=cats.replace('-', ' '))
context = {'cats':cats.replace('-', ' ').title(), 'category_posts':category_posts}
return context
Here is my URLS:
path('category/<str:cats>/', CategoryClassView.as_view(), name='category')
Here is my template:
{% extends "base.html" %}
{% block content %}
{% for category in category_list %}
<div >
<div >
<span ><a href="">{{ category.name}}</a></span> ·
</div>
</div>
{% endfor %}
{% endblock content %}
Could you write a more detailed explanation for your answer? Why is just passing {% url 'category' %} is not working? A link to a list of useful materials would be also acceptable for better understanding.
CodePudding user response:
You should be doing this way, since you are having parameters in the url:
{% url 'category' cats=category.name %}
Also you can use as:
{% url 'category' %}?cats={{ category.name }}