2017-06-11 67 views
2

在Chrome中,我必須手動輸入http://127.0.0.1:8000/music/1/才能進入我想要的頁面。 (我想去第1頁)。爲什麼我的鏈接無法導航到我想要點擊的頁面?

但是,當我嘗試點擊鏈接時,我想會帶我到我想要的地方http://127.0.0.1:8000/music,例如Red。這需要我的錯誤頁面:

enter image description hereenter image description here

這裏是我的views.py

from django.http import HttpResponse 
from django.shortcuts import loader 
from .models import Album 

def index(request): 
    all_albums = Album.objects.all() 
    template = loader.get_template('music/index.html') 
    context = { 
     'all_albums': all_albums, 
    } 
    return HttpResponse(template.render(context, request)) 

def detail(request, album_id): 
    return HttpResponse("<h2>Details for album id: " + str(album_id) + "</h2>") 

這裏是我的urls.py

from django.conf.urls import url 
from . import views 

urlpatterns = [ 
    url(r'^$', views.index, name = 'index'), 

    url(r'^(?P<album_id>[0-9]+)/$', views.detail, name = 'detail'), 
] 

這裏是我的`的index.html

{% if all_albums %} <!-- Will be true as long as it has at least 1 album --> 
    <h3>Here are all my albums</h3> 
<ul> 
    {% for album in all_albums %} 
    <li><a href="/music/id/{{ album.id }}">{{ album.album_title }}</a></li> 
    {% endfor %} 
</ul> 
{% else %} 
    <h3>You don't have any albums</h3> 
{% endif %} 
+0

你是如何在你的模板中寫入「Red」的?是否像''{%url'your_app_name:detail'album_id%}''? – Liliane

+0

@Liliane我發佈了我的index.html文件 – bojack

+0

如果你改變鏈接到''/ music/{{album.id}} /''它會讓你登陸一個正確的頁面嗎? – Liliane

回答

2

模板中有錯誤。而不是/music/id/{{ album.id }}你應該有/music/{{ album.id }}/。當您點擊鏈接Red時,它會將您重定向到music/id/1而不是music/1。所以你會得到一個404錯誤。

+1

太簡單了!非常感謝:D – bojack

+0

@bojack你應該考慮在''urlpatterns''之前加''app_name ='[把你的應用的實際名稱]''''。這樣你可以建立鏈接爲''{%url'your_app_name:detail'album_id%}''。我建議你通過官方[Django民意調查教程](https://docs.djangoproject.com/en/1.11/intro/tutorial01/)(它有七個部分)。 – Liliane

相關問題