Tuesday, 26 March 2019

django 21 DetailView

created 4 songs in the album

deleted 1 song, browser stays in the album detail page

#music/urls

from django.urls import path
from . import views

app_name = 'music'

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

    path('register/', views.UserRegistration.as_view(), name='register'),

    path('login/', views.UserLogin.as_view(), name='login'),

    path('logout/', views.UserLogout, name='logout'),

    #/music/id/
    path('<pk>/', views.DetailView.as_view(), name='detail'),

    #music/album/add/
    path('album/add/', views.AlbumCreate.as_view(), name='album-add'),

    #music/album/id/
    path('album/<pk>/', views.AlbumUpdate.as_view(), name='album-update'),

    #music/album/id/delete/
    path('album/<pk>/delete/', views.AlbumDelete.as_view(), name='album-delete'),

    #music/song/add/
    path('song/add/', views.SongCreate.as_view(), name='song-add'),

    #music/song/id/
    path('song/<pk>/', views.SongUpdate.as_view(), name='song-update'),

    #music/song/id/delete/
    path('song/<album_pk>/<pk>/delete/', views.SongDelete.as_view(), name='song-delete'),
]

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

from django.views import generic
from .models import Album, Song
from django.views.generic.edit import  CreateView, UpdateView, DeleteView, View
from django.urls import reverse_lazy
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from .forms import RegistrationForm, LoginForm
from django.contrib.auth.mixins import LoginRequiredMixin

class IndexView(generic.ListView):
    template_name = 'music/index.html'

    def get_queryset(self):
        return  Album.objects.all()

class DetailView(generic.DetailView):
    model = Album
    template_name = 'music/detail.html'

#protected route, require authentication
class AlbumCreate(LoginRequiredMixin, CreateView):
    model = Album
    fields = ['artist', 'album_title', 'genre', 'album_logo']

class AlbumUpdate(LoginRequiredMixin, UpdateView):
    model = Album
    fields = ['artist', 'album_title', 'genre', 'album_logo']

class AlbumDelete(LoginRequiredMixin, DeleteView):
    model = Album
    #redirect to home page after delete
    success_url = reverse_lazy('music:index')

#protected route, require authentication
class SongCreate(LoginRequiredMixin, CreateView):
    model = Song
    fields = ['album', 'file_type', 'song_title', 'is_favorite']

class SongUpdate(LoginRequiredMixin, UpdateView):
    model = Song
    fields = ['album', 'file_type', 'song_title', 'is_favorite']

class SongDelete(LoginRequiredMixin, DeleteView):
    model = Song
    #redirect to detail page after delete
    def get_success_url(self):
        return  reverse_lazy('music:detail',kwargs={'pk': self.kwargs['album_pk']})

#user registration
class UserRegistration(View):
    form_class = RegistrationForm
    template_name = 'music/registration_form.html'

    def get(self, request):
        #get request, display UserForm with empty fields
        form = self.form_class(None)
        return render(request, self.template_name, {'form': form})

    def post(self, request):
        form = self.form_class(request.POST)

        if form.is_valid():

            user = form.save(commit=False)

            #clearned/normalized data
            password = form.cleaned_data['password']

            user.set_password(password)
            user.save()

            return redirect('music:login')

        return render(request, self.template_name, {'form': form})

#user login
class UserLogin(View):
    form_class = LoginForm
    template_name = 'music/login_form.html'

    def get(self, request):
        #get request, display UserForm with empty fields
        form = self.form_class(None)
        return render(request, self.template_name, {'form': form})

    def post(self, request):
        form = self.form_class(request.POST)

        if form.is_valid():

            #clearned/normalized data
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']

            #returns User objects if credentials are correct
            user = authenticate(username=username, password=password)

            if user is not None:

                if user.is_active:
                    login(request, user)
                    return redirect('music:index')

        return render(request, self.template_name, {'form': form})

def UserLogout(request):
    logout(request)
    return redirect('music:index')

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

{% extends 'music/base.html' %}
{% block title %}Songs{% endblock %}

{% block body %}

    <div class="row">
        <div class="col">
            <img style="height: 150px; margin-bottom: 20px;" src="{{album.album_logo.url}}"><br>
            <h4>Title: {{album.album_title}}</h4>
            <h4>Artist: {{album.artist}}</h4>
            <h4>Genre: {{album.genre}}</h4>
        </div>

        <div class="col">
            <div>
                <a href="{% url 'music:song-add'%}" class="btn btn-success btn-sm" role="button">
                    <span class="glyphicon glyphicon-plus" aria-hidden="true"></span> Add Song
                </a>
            </div>

            <ul class="list-group list-group-flush">
                {% for song in album.song_set.all %}
                    <li class="list-group-item d-flex justify-content-between align-items-center">
                        <div>
                            {{ song.song_title }}

                            {% if song.is_favorite %}
                                <span class="glyphicon glyphicon-heart" aria-hidden="true"></span>
                            {% endif %}
                        </div>

                        <div>
                            <!-- Edit -->
                            <form action="{% url 'music:song-update' song.id %}" method="post" style="display: inline;">
                                {% csrf_token %}
                                <input type="hidden" name="song_id" value="{{song.id}}"/>
                                <button type="submit" class="btn btn-default btn-sm">
                                    <span class="glyphicon glyphicon-pencil"></span>
                                </button>
                            </form>

                             <!-- Delete -->
                            <form action="{% url 'music:song-delete' album.id song.id  %}" method="post" style="display: inline;">
                                {% csrf_token %}
                                <input type="hidden" name="song_id" value="{{song.id}}"/>
                                <button type="submit" class="btn btn-default btn-sm">
                                    <span class="glyphicon glyphicon-trash"></span>
                                </button>
                            </form>
                        </div>
                    </li>
                {% endfor %}
            </ul>
        </div>
    </div>

{% endblock %}

No comments:

Post a Comment