Answer the question
In order to leave comments, you need to log in
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)
path('category/<int:category_id>/', NewsByCategory.as_view(extra_context={'title': 'Какой-то тайтл'}),
name='category'),
@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}
<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>
<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>
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question