How do I make custom filters work in Django_filters?

So I've made this custom filter in filters.py with Django-filters and when I'm submitting the "YEAR CHOICE" the page refreshes but it doesn't work. I think my "year_filter_method" is not working also I want my pagination and filter system to work together. Any help would be really appreciated. Cheers!

**Note it doesn't work with or without pagination.

models.py

from django.db import models
import datetime

YEAR_CHOICES = []
for r in range(2000, (datetime.datetime.now().year + 1)):
    YEAR_CHOICES.append((r, r))


class Music(models.Model):
    Song = models.CharField(max_length=100, blank=False)
    Year = models.IntegerField(('year'), choices=YEAR_CHOICES, default=datetime.datetime.now().year)

    def __str__(self):
        return self.Song

filters.py

import django_filters
import datetime

class MusicFilter(django_filters.FilterSet):


    YEARCHOICES = []
    for r in range(2010, (datetime.datetime.now().year + 1)):
        YEARCHOICES.append((r, r))


    year_filter = django_filters.ChoiceFilter(label="Year", choices=YEARCHOICES, method="year_filter_method")

    def year_filter_method(self, queryset):
        expression = Music.Year
        return queryset.filter(expression)

views.py

def music_page(request):

    #pagination & filter

    music = Music.objects.all().order_by('-id')
    music_filter = MusicFilter(request.GET, queryset=music)
    paginator = Paginator(music, 6)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    try:
        music = paginator.page(page_number)
    except PageNotAnInteger:
        music = paginator.page(1)
    except EmptyPage:
        music.paginator.page(paginator.num_pages)

    return render(request, template_name='main/music.html', context={'music': music, 'page_obj': page_obj, 'filter': music_filter})

filters.html

{% load static %}

<link rel="stylesheet" href="{% static 'main/filter.css' %}" type="text/css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<div class="container">
    <form method="get">
        <span class="label">{{filter.form}}</span>
        <span class="btn-search-handler"><button id="search_btn_id" type="submit">Search</button></span>
    </form>
</div>

music.html

{% include 'main/includes/navbar.html' %}

{% include 'main/includes/filter.html' %}

<div class='card'>
    {% for m in music %}
        <div class='year'>{{m.Year}}</div>
        <div class='song_name'>{{m.song}}</div>
</div>

{% include 'main/includes/pagination.html' %}

{% include 'main/includes/footer.html' %}


Read more here: https://stackoverflow.com/questions/64485483/how-do-i-make-custom-filters-work-in-django-filters

Content Attribution

This content was originally published by Zeniel at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: