Django href for html

Viewed 50

How i can make link to this urls.py? I tried to pass the link through all the methods I know but they don't work and gave an error

    path('category/<slug:gender_slug>/<slug:category_slug>/', views.StuffCategory.as_view(), name='category'),

html:

{% get_genders as genders %}
                    {% for gender in genders %}
                <li>
                    <!-- First Tier Drop Down -->
                    <label for="drop-2" class="toggle">Категории <span class="fa fa-angle-down"
                                                                       aria-hidden="true"></span> </label>

                    <a href="/">{{ gender }} <span class="fa fa-angle-down" aria-hidden="true"></span></a>
                    <input type="checkbox" id="drop-2">

                    <ul>
                        {% get_categories as categories %}
                        {% for category in categories %}
                        <li><a href="/">{{category.name}}</a></li>
                        {% endfor %}
                    </ul>
                </li>
                    {% endfor %}

views.py

class StuffCategory(ListView):
    model = Stuff
    template_name = 'shop/shop.html'
    context_object_name = 'stuffs'

    def get_queryset(self):
        queryset = Stuff.objects.filter(draft=False)
        if self.kwargs.get('category_slug'):
            queryset = queryset.filter(category__slug=self.kwargs['category_slug'])
        if self.kwargs.get('gender_slug'):
            queryset = queryset.filter(gender__slug=self.kwargs['gender_slug'])
        return queryset
2 Answers

Just pass the parameters that have been defined in url as below:

<a href="{% url 'category' gender_slug=gender.slug category_slug=category.slug %}">{{category.name}}</a>

For more information refer to official docs

When trying to access a link with a href attribute you can simply use the name attribute of your path object that you defined in urls.py. You have to make sure, to submit every parameter the path object needs:

For example for an edit field:

<li><a href="{% url 'category' object.pk gender_slug=gender arg %}">

here:

  • category is the name
  • object.pk could be the primary key of the object transmitted to the template
  • gender_slug & arg are additional parameters that are defined by your path object
Related