一千萬個為什麽

搜索

Django:命名URL /相同模板,不同的命名URL

我有一個webapp,它會在點擊相應的鏈接時列出我的所有藝術家,專輯和歌曲。我廣泛使用通用視圖(object_list/detail)和命名網址,但我遇到了煩惱。我有三個模板幾乎輸出完全相同的html,看起來像這樣:

{% extends "base.html" %}
{% block content %}
<div id="content">


    {% for song in songs_list %}
  • {{ song.title }}
  • {% endfor %}
</div>
{% endblock content %}

My artist and album template look pretty much the same and I'd like to combine the three template's into one. The fact that my variables start with song can easily be changed to the default obj. It's my

    named url I don't know how to correct. Obviously I want it to link to a specific album/artist/song using the named urls in my urls.pybut I don't know how to make it context aware. Any suggestions?

    urls.py:

urlpatterns = patterns('tlkmusic.apps.tlkmusic_base.views',
    # (r'^$', index),
    url(r'^artists/$', artist_list, name='artist_list'),
    url(r'^artists/(?P\w)/$', artist_list, name='artist_list_x'),
    url(r'^artist/(?P\d+)/$', artist_detail, name='artist_detail'),
    url(r'^albums/$', album_list, name='album_list'),
    url(r'^albums/(?P\w)/$', album_list, name='album_list_x'),
    url(r'^album/(?P\w)/$', album_detail, name='album_detail'),
    url(r'^songs/$', song_list, name='song_list'),
    url(r'^songs/(?P\w)/$', song_list, name='song_list_x'),
    url(r'^song/(?P\w)/$', song_detail, name='song_detail'),
)

最佳答案

您可以為通用object_type定義網址格式,而不是為藝術家,專輯和歌曲單獨定義:

urlpatterns = patterns('tlkmusic.apps.tlkmusic_base.views',
    # (r'^$', index),
    url(r'^(?P\w+)/$', music_object_list, name='music_object_list'),
    url(r'^(?P\w+)/(?P\w)/$', music_object_list, name='music_object_list_x'),
    url(r'^(?P\w+)/(?P\d+)/$', music_object_detail, name='music_object_detail'),

)

然後在您的模板中,您的網址標記變為

{% url music_object_list_x object_type starts_with %} *

您可能會發現只需要一個視圖, music_object_list 。如果您發現每個對象類型需要不同的函數,則在 music_object_list 中調用各個函數。

def music_object_list(request, object_type, starts_with=None):
     if object_type == 'artists':
         return artist_list(request, starts_with=starts_with)
     elif object_type == 'albums':
         return album_list(request, starts_with=starts_with)
     ...

如果您使用的是 django.views.generic.list_detail.object_list ,請記住將 object_type 添加到 extra_context 字典中。這會將object_type添加到模板上下文中,從而允許url標記起作用。

extra_context = {'object_type': 'songs', ...}

*這是Django 1.2的新url標記語法。對於舊版本,您將使用逗號。

{% url music_object_list_x object_type,starts_with %}

請參閱文檔(當前1.1 )了解更多信息

轉載註明原文: Django:命名URL /相同模板,不同的命名URL