V
V
Vlad2021-02-14 16:50:23
Django
Vlad, 2021-02-14 16:50:23

How to use self.kwargs outside of CBV?

I started to study Django and ran into such a problem. Tell me, please, is it possible to somehow use the construction self.kwargs[]outside the Class Based View?

Let me explain:
There is an idea:

Сlass NewsByCategory(ListView): 
        model = News
        template_name = 'news/home_news_list.html'
        context_object_name = 'news'
        allow_empty = False
    
        def get_context_data(self, *, object_list=None, **kwargs):
            context = super().get_context_data(**kwargs)  # контекст модели
            context['title'] = Category.objects.get(pk=self.kwargs['category_id'])  
            return context
    
        def get_queryset(self):
            return News.objects.filter(category_id=self.kwargs['category_id'], is_published=True)

There is a path from url.py:

path('category/<int:category_id>/', NewsByCategory.as_view(extra_context={'title': 'Какой-то тайтл'}),
             name='category'),


And there is a custom tag:

@register.inclusion_tag('news/list_categories.html')
    def show_categories(arg1='Hello', arg2='World'):
        categories = Category.objects.all()
        return {'categories': categories, 'arg1': arg1, 'arg2': arg2}

This custom tag renders the template:

<div class="list-group">
        {%for item in categories%}
        <a href="{{ item.get_absolute_url }}" class="list-group-item list-group-item-action">{{item.title}}</a>
        {% endif %}
        {%endfor%}
    </div>


Why do I need it: Now, with the help of this tag, a side panel is created in which links to news with a specific category are displayed. So I would like that on the page with news of a certain category, the link to the same page was not active. those. if, for example, a page with news about sports is open, then we would like the links to all other pages, except for the current one, to be active in the sidebar.

Here's how I roughly see the sidebar template:

<div class="list-group">
        {%for item in categories%}
        {% if item.pk !=  self.kwargs['category_id'] %}
        <a href="{{ item.get_absolute_url }}" class="list-group-item list-group-item-action">{{item.title}}</a>
        {% elif %}
        <p class="selected">{{item.title}}</p>
        {% endif %}
        {%endfor%}
    </div>


It remains to understand how to implement this in a custom tag ...

Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2021-02-14
@Vlad1987

Pass category to a custom tag as a parameter, or pass the entire context in general (takes_context=True)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question