Wednesday 6 March 2019

django 12 dynamic url

#music/templates/music/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Albums</title>
</head>
<body>

    {% if all_albums %}
        <ul>
            {% for album in all_albums %}
                <li><a href="{% url 'music:detail' album.id %}">{{ album.album_title }}</a></li>
            {% endfor %}
        </ul>
    {% else %}
        <h3>There is no album</h3>
    {% endif %}
</body>
</html>

------------------------------
#music/urls

from django.urls import path
from . import views

app_name = 'music'

urlpatterns = [
    path('', views.index, name='index'),

    #/music/id/
    path('<album_id>/', views.detail, name='detail'),
]

-------------------------------
#music/views

from .models import Album
from django.shortcuts import render, get_object_or_404

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

def detail(request, album_id):
    album = get_object_or_404(Album, pk=album_id)
    return render(request, 'music/detail.html', {'album': album})

No comments:

Post a Comment