我想删除一个硬编码的URL,并使用一个动态编码的URL并将其加载到服务器上,但我收到了一个错误:TemplateSyntaxError at/music/第6行上的块标记无效:"path",应为"empty"或"endfor"。你忘记注册或加载这个标签了吗?
这是我的代码:
index.html:
{% if all_albums %}
<h3>here are all my albums:</h3>
<ul>
{% for album in all_albums %}
<li><a href = "{% path 'music:detail' album.id %}"> {{ album.album_title }}</a></li>
{% endfor %}
</ul>
{% else %}
<h3>You don't have any Albums</h3>
{% endif %}
music.urls.py:
from django.urls import path
from . import views
app_name = 'music'
urlpatterns = [
# /music/
path('', views.index, name='index'),
# /music/712/
path('<int:album_id>/', views.detail, name='detail'),
]
music.views.py:
from django.shortcuts import render, get_object_or_404
from .models import Album
# noinspection PyUnusedLocal
def index(request):
all_albums = Album.objects.all()
return render(request, 'music/index.html', {'all_albums': all_albums})
# noinspection PyUnusedLocal
def detail(request, album_id):
album = get_object_or_404(Album, pk=album_id)
return render(request, 'music/detail.html', {'album': album})
Analytic_practic.urls:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('music/', include('music.urls')),
]
试试这个:
<li><a href = "{% url 'music:detail' album.id %}"> {{ album.album_title }}</a></li>
而不是这个:
<li><a href = "{% path 'music:detail' album.id %}"> {{ album.album_title }}</a></li>