Skip to main content
 首页 » 编程设计

python之为什么我的链接在单击后无法导航到我想要的页面

2024年10月01日7zhujiabin

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

但是,当我尝试单击我认为可以将我带到 http://127.0.0.1:8000/music 中所需位置的链接时,例如,Red。它将我带到那个错误页面:

这是我的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 %} 

请您参考如下方法:

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