Reputation: 159
I have two models:
class Button(models.Model):
title = models.CharField(max_length=100,)
anchor = models.ForeignKey(Section, on_delete=models.CASCADE,
related_name='anchor', blank=True, null=True,)
class Section(models.Model):
...
transliterate_name = models.CharField(max_length=100, blank=True,
null=True)
Now I wanna to get transliterate_name in my template. I use this field as id to article. And i want to assign it to the button id in navigation menu. There is my template:
<ul class="navbar-nav">
{% for menu_btn in menu_buttons %}
<li class="nav-item">
<a href="#{{ ??? }}" class="nav-link">
{{ menu_btn.title }}
</a>
</li>
{% endfor %}
</ul>
in my views:
class SectionView(ListView):
queryset = Section.objects.filter(name_visible=True)
context_object_name = 'sections'
extra_context = {
'articles': Article.objects.all(),
'menu_buttons': Buttons.objects.all(),
}
template_name = 'sections/sections.html'
Any advise please.
Upvotes: 2
Views: 1042
Reputation: 476614
You can obtain the related Section
object, by fetching the anchor
attribute:
<a href="#{{ menu_btn.anchor.transliterate_name }}" class="nav-link">
Since you will fetch the related attribute of every Button
object, it it better to fetch all these Section
s in one fetch with .select_related(..)
:
class SectionView(ListView):
queryset = Section.objects.filter(name_visible=True)
context_object_name = 'sections'
extra_context = {
'articles': Article.objects.all(),
'menu_buttons': Buttons.objects.select_related('anchor').all(),
}
template_name = 'sections/sections.html'
Upvotes: 1