当点击相应链接时,我的Web应用程序会列出所有的艺术家、专辑和歌曲。我广泛使用通用视图(object_list/detail)和命名URL,但是我遇到了一个麻烦。我有三个模板,几乎输出完全相同的HTML,就像这样:
{% extends "base.html" %}
{% block content %}
<div id="content">
<ul id="starts-with">
{% for starts_with in starts_with_list %}
<li><a href="{% url song_list_x starts_with %}">{{ starts_with|upper }}</a></li>
{% endfor %}
</ul>
<ul>
{% for song in songs_list %}
<li>{{ song.title }}</li>
{% endfor %}
</ul>
</div>
{% endblock content %}
我的艺术家和专辑模板看起来几乎一样,我想把这三个模板合并成一个。我的变量以
song
开头的事实可以很容易地更改为默认的obj
。问题是我不知道如何更正<ul id="starts-with">
命名的URL。显然,我希望它使用我的urls.py
中的命名URL链接到特定的专辑/艺术家/歌曲,但我不知道如何使其具有上下文感知能力。有什么建议吗?
urls.py:urlpatterns = patterns('tlkmusic.apps.tlkmusic_base.views',
# (r'^$', index),
url(r'^artists/$', artist_list, name='artist_list'),
url(r'^artists/(?P<starts_with>\w)/$', artist_list, name='artist_list_x'),
url(r'^artist/(?P<artist_id>\d+)/$', artist_detail, name='artist_detail'),
url(r'^albums/$', album_list, name='album_list'),
url(r'^albums/(?P<starts_with>\w)/$', album_list, name='album_list_x'),
url(r'^album/(?P<album_id>\w)/$', album_detail, name='album_detail'),
url(r'^songs/$', song_list, name='song_list'),
url(r'^songs/(?P<starts_with>\w)/$', song_list, name='song_list_x'),
url(r'^song/(?P<song_id>\w)/$', song_detail, name='song_detail'),
)
object_list
作为函数名似乎与from django.views.generic.list_detail import object_list
冲突,但这很容易克服。我会回来分享我的发现! - TheLizardKingmusic_object_list
。 - Alasdair{% url music_object_list_x object_type,starts_with %}
时很难让它识别出object_type。我正在使用Django 1.1.1版本。 - TheLizardKingextra_context = {'starts_with_list': starts_with_list, 'object_type': 'songs'}
来解决了。 - TheLizardKingobject_type
添加到extra_context
中,但我看到你已经解决了! - Alasdair