为什么我的链接会在点击后导航到我想要的页面?

时间:2017-06-11 11:14:55

标签: python django

在Chrome中,我必须手动输入http://127.0.0.1:8000/music/1/才能进入我想要的页面。 (我想转到第1页)。

然而,当我尝试点击我认为会带我到http://127.0.0.1:8000/music所需的链接时,例如Red。它带我到那个错误页面:

enter image description here enter 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 %}

1 个答案:

答案 0 :(得分:2)

模板中出现错误。而不是/music/id/{{ album.id }}您应该/music/{{ album.id }}/。当您点击链接Red时,它会将您重定向到music/id/1而不是music/1。所以你得到404错误。