Reputation: 1
Please, I need your help.
I can't return urls from model to template. I think that problem in method get_absolute_url
. This is the error that I get:
NoReverseMatch at /
Reverse for 'product_list' with arguments '('saws',)' not found. 1 pattern(s) tried: ['$']
Code is:
# models
class Category(models.Model):
name = models.CharField(verbose_name='Category', max_length=100, db_index=True)
slug = models.SlugField(max_length=100, db_index=True,
unique=True)
...
def get_absolute_url(self):
return reverse('core:product_list',
args=[self.slug])
urls.py
app_name = 'core'
urlpatterns = [
path('', views.ProductView.as_view(), name='product_list'),]
#url(r'^$', views.ProductView.as_view(), name='product_list'),
views.py
class ProductView(generic.ListView):
queryset = Product.objects.filter(available=True)
paginate_by = 3
form_class = QuantityForm
categories = Category.objects.all()
def category_slugg(self, category_slug=None):
if category_slug:
category = get_object_or_404(Category, slug=category_slug)
return category
def get_context_data(self, **kwargs):
context = super(ProductView, self).get_context_data(**kwargs)
context['Products'] = self.form_class
context['categories'] = self.categories
context['category'] = self.category_slugg
return context
html
<li {% if not category %}class="selected"{% endif %}>
<a href="{{ categories.get_absolute_url }}"All</a>
</li>
{% for c in categories %}
<a href="{{ c.get_absolute_url }}">{{ c.name }}</a> <!--if delete 'c.get_absolute_url', except escape-->
{% endfor %}
Upvotes: 0
Views: 748
Reputation: 117
Try changing args=[self.slug]
to kwargs={'slug': self.slug}
, then in urls.py:
urlpatterns = [
path('<str:slug>/', views.ProductView.as_view(), name='product_list'),
]
The idea is that get_absolute_url receives kwargs from urls.
Upvotes: 0
Reputation: 12869
Your url path
doesn't accept any args but then you pass it a slug.
You need to allow the slug in the URL;
path('<slug:category_slug>/', views.ProductView.as_view(), name='product_list'),
There's an example of this in the django docs here; https://docs.djangoproject.com/en/3.0/topics/http/urls/#examples
Upvotes: 2