Friday, 8 March 2019

django 13 form

#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/id/favorite/
    path('<album_id>/favorite/', views.favorite, name='favorite'),
]

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

from .models import Album, Song
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})

def favorite(request, album_id):
    album = get_object_or_404(Album, pk=album_id)
    try:
        selected_song = album.song_set.get(pk=request.POST['song'])
    except (KeyError, Song.DoesNotExist):
        return render(request, 'music/detail.html', {
            'album': album,
            'error_message': 'You did not select a valid song',
        })
    else:
         if selected_song.is_favorite:
            selected_song.is_favorite = False
        else:
            selected_song.is_favorite = True
        selected_song.save()
        return render(request, 'music/detail.html', {'album': album})

-----------------------------------
#music/templates/music/detail

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Detail</title>
</head>
<body>
    <img src="{{album.album_logo}}">
    <h1>{{album.album_title}}</h1>
    <h3>{{album.artist}}</h3>

    {% if error_message %}
        <p><strong>{{error_message}}</strong></p>
    {% endif %}

    <form action="{% url 'music:favorite' album.id %}" method="post">
        {% csrf_token %}
        {% for song in album.song_set.all %}
            <input type="radio" id="song{{forloop.counter}}" name="song" value="{{song.id}}" />
            <label for="song{{ forloop.counter}}">
                {{ song.song_title }}
                {% if song.is_favorite %}
                    <img src="https://img.icons8.com/material/24/000000/star.png"><br>
                {% endif %}
            </label><br>
        {% endfor %}
        <input type="submit" value="Favorite">
    </form>
</body>
</html>

No comments:

Post a Comment