Reputation: 1340
I'm building a site with Django 1.5.1. I have Album and Category models defined:
###models.py
class Category(models.Model):
title = models.CharField(max_length=200, unique=True)
class Album(models.Model):
category = models.ForeignKey(Category, related_name='albums')
I've generated a menu to list automatically Categories and their related Albums with this view and template:
###views.py
def index(request):
categories = Category.objects.all()[:5]
context = {'categories': categories}
return render(request, 'gallery/index.html', context)
def detail(request, album_id):
album = get_object_or_404(Album, pk=album_id)
return render(request, 'gallery/detail.html', {'album': album})
###index.html
{% for category in categories %}
{% with category.albums.all as albums %}
{{ category.title }}
{% if albums %}
{% for album in albums %}
<a href="/gallery/{{ album.id }}/">{{ album.title }}</a><br>
{% endfor %}
{% endif %}
{% endwith %}
{% endfor %}
<a href="blah">Biography</a>
I also have a view to show each album as a gallery indicates to detail.html. I want to show menu list beside each gallery so I used {% include "gallery/index.html" %}
tag at the begining of detail.html. But menu list doesn't show up when detail.html loads, I just see Biography fixed link.
Here is my question: How should I import menu list generated in index.html in detail.html too?
Upvotes: 1
Views: 2573
Reputation: 29794
index.html
expects to receive categories
variable in order to create the menu. If you want to include it in some other template you have to pass the categories
variable to the other template for the included one. If you have some conflicts with names you can also pass variables to the include
tag like this:
{% include 'include_template.html' with foo=bar%}
So the included template can use the variable foo
which has the value bar
.
For example, you need to pass the categories
variable to the context generating for the detail.html
like this:
def detail(request, album_id):
categories = Category.objects.all()[:5]
album = get_object_or_404(Album, pk=album_id)
return render(request,
'gallery/detail.html',
{'album': album,
'categories':categories}
)
And the line that includes the index.html
template inside the detail.html
template should remain like it is in the question:
{% include "gallery/index.html" %}
What I just did was pass the categories
variable needed by index.html
for rendering the menu to the detail.html
template, which in turn, will pass it to all included template (index.html
).
That should get the menu working from within detail.html
template.
Hope it helps.
Upvotes: 3