简体   繁体   中英

Django: Reverse URL patterns not found

I am trying to make regex (Django URL) work with with the queryset. I tried different patterns with template URL but it didn't work.

Generic ListView:

class ProductListView(ListView):
    template_name = "main/product_list.html"
    paginate_by = 4

    def get_queryset(self):
        tag = self.kwargs["tag"]
        self.tag = None

        if tag != "all":
            self.tag = get_object_or_404(
                models.ProductTag, slug=tag
            )

        if self.tag:
            products = models.Product.objects.active().filter(
                tags=self.tag
            )
        else:
            products = models.Product.objects.active()

        return products.order_by("name")

My URL:

path("products/<slug:tag>/", views.ProductListView.as_view(), name='products'),

Template:

I couldn't get it work in tempalte like below. I tried passing different keyword arguments but it is not working:

<li class="nav-item">
    <a class="nav-link" href="{% url 'products' %}">Products</a>
</li>

Error:

Reverse for 'products' with arguments '('',)' not found. 1 pattern(s) tried: ['products\\/(?P<tag>[-a-zA-Z0-9_]+)\\/$']

Your products route expects a slug argument. So you have to give it one.

It has to be something like

<li class="nav-item">
    <a class="nav-link" href="{% url 'products' 'my-nice-slug' %}">Products</a>
</li>

In this case my-nice-slug should of course be some existing slug.

The previous answer is correct, the exact url you want is simply -

{% url 'products' product.slug %}

if the product has a slug field in its model which contains the slug or -

{% url 'products' product.tag %}

if the product has a tag field in its model which contains the slug.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM