Sunday 21 April 2019

django 30 filter by query

default 4 post/page, author all

change author to bob, only show bob's posts

change to 6 posts/page, still only show bob's posts
url http://127.0.0.1:8000/music/?postNum=6&userName=bob

select 2nd page, still show 6 posts/page, only bob's posts
url http://127.0.0.1:8000/music/?postNum=6&userName=bob&page=2

#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, UserPassesTestMixin
from django.contrib import messages
from django.contrib.auth.models import User

post_num = 4
author_name = None
#get list of username
author_names = []
for author in User.objects.all():
    author_names.append(author.username)

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

    def get_paginate_by(self, queryset):
        global post_num
        post_num = self.request.GET.get('postNum', self.paginate_by)
        return post_num

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        context['post_num'] = post_num
        context['author_name'] = author_name
        context['all_authors_names'] = author_names
        return context

    def get_queryset(self):
        global author_name
        author_name = self.request.GET.get('userName', None)

        if(author_name not in [None,'None','All']):
            author_id = User.objects.get(username=author_name).pk
            return  Album.objects.filter(author=author_id).order_by('-date_posted')
        else:
            return Album.objects.all()

---------------------------------------------
#templates/index

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

{% block body %}
    <div class="container-fluid">
        <div class="row justify-content-end align-items-center pr-4">
            <form action="" method="get" >
                posts
                <select name="postNum" onchange="this.form.submit()">
                    <option>{{post_num}}</option>
                    <option>2</option>
                    <option>3</option>
                    <option>4</option>
                    <option>6</option>
                    <option>8</option>
                    <option>12</option>
                    <option>16</option>
                </select>
                <input type="hidden" name="userName" value={{author_name}}>
            </form>
            &nbsp &nbsp
            <form action="" method="get" >
                author
                <select name="userName" onchange="this.form.submit()">
                    <option>{{author_name}}</option>
                    <option>All</option>
                    {% for author in all_authors_names %}
                        <option>{{author}}</option>
                    {% endfor %}
                </select>
                <input type="hidden" name="postNum" value={{post_num}}>
            </form>
        </div>
        <div class="row mt-4">
            {% for album in object_list %}
                <div class="col" style="margin-left: auto; margin-right: auto; margin-top: 5px; margin-bottom: 5px;">
                    <div class="card" style="width: 200px;">
                        <img src="{{album.album_logo.url}}" class="card-img-top" style="height: 150px" alt="{{album.album_title}}">

                        <div class="card-body">
                            <div style="height: 40px"><h5 class="card-title">Album: {{album.album_title}}</h5></div>
                            <div style="height: 40px"><p class="card-text">Artist: {{album.artist}}</p></div>

                            <!-- Detail -->
                            <a href="{% url 'music:detail' album.id %}" class="btn btn-primary btn-sm">View Detail</a>

                            <!-- Edit -->
                            <a class="btn btn-default btn-sm" href="{% url 'music:album-update' album.id %}">
                                <span class="glyphicon glyphicon-pencil"></span>
                            </a>

                            <!-- Delete -->
                            <a class="btn btn-default btn-sm" href="{% url 'music:album-delete' album.id %}">
                                <span class="glyphicon glyphicon-trash"></span>
                            </a>

                        </div>

                        <div class="card-footer text-muted">
                            Created by {{album.author}} @ {{album.date_posted}}
                        </div>
                    </div>
                </div>
            {% endfor %}
        </div>
        <div class="row justify-content-between align-items-center mt-4">
            <div>
                {% if is_paginated %}
                    {% if page_obj.has_previous %}
                        <a class="btn btn-pagination" href="?postNum={{post_num}}&userName={{author_name}}&page=1" >First</a>
                        <a class="btn btn-pagination" href="?postNum={{post_num}}&userName={{author_name}}&page={{page_obj.previous_page_number}}">Previous</a>
                    {% endif %}

                    {% for num in page_obj.paginator.page_range %}
                        {% if page_obj.number == num %}
                            <a class="btn btn-primary" href="?postNum={{post_num}}&userName={{author_name}}&page={{ num }}">{{ num }}</a>
                        {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
                            <a class="btn btn-pagination" href="?postNum={{post_num}}&userName={{author_name}}&page={{ num }}">{{ num }}</a>
                        {% endif %}
                    {% endfor %}

                    {% if page_obj.has_next %}
                        <a class="btn btn-pagination" href="?postNum={{post_num}}&userName={{author_name}}&page={{ page_obj.next_page_number }}">Next</a>
                        <a class="btn btn-pagination" href="?postNum={{post_num}}&userName={{author_name}}&page={{page_obj.paginator.num_pages}}">Last</a>
                    {% endif %}
                {% endif %}
            </div>
        </div>
    </div>
{% endblock %}

reference:
https://www.django-rest-framework.org/api-guide/filtering/
https://stackoverflow.com/questions/15044778/how-to-get-user-id-from-auth-user-table-in-django

No comments:

Post a Comment