1

I have a problem and i dont know how to solve it. I got this template generating /list/a,b,c, etc. And i want to show in this a,b,c url only model with the same letter.

list template

<div class="panel-body anime-list text-center">
    <div class="btn-group btn-group-xs">
        {% for i in alphabet %}
            <a href="{{i}}" class="btn">{{i}}</a>
        {%endfor%}
    </div>
</div>

model's

class Anime(models.Model):
    title = models.CharField(max_length=300, unique=True)
    ongoing = models.BooleanField(default=True)
    add_date = models.DateTimeField('date published')

How can i filter that in another desired template

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
Rafalpero
  • 97
  • 1
  • 2
  • 10

3 Answers3

1

in your template tags module you should define the following simple tag :

from django import template

register = template.Library()

@register.simple_tag
def filterAnime(char):
    return Anime.objects.filter(title__startswith=char)

then you can use this tag in your template as follow:

{% load my_tags %}
<div class="panel-body anime-list text-center">
    <div class="btn-group btn-group-xs">
        {% for i in alphabet %}
            <a href="{{i}}" class="btn">{{i}}</a>
            {%filterAnime i as filterdObjs%}
            //do what ever you want
        {%endfor%}
    </div>
</div>
adnanmuttaleb
  • 3,388
  • 1
  • 29
  • 46
0

In your template do:

<a href="{% url 'list_view' letter=i %}" class="btn">{{i}}</a>

The goal is to get the letter into the view, done here by having it as a URL parameter.

In your urls.py:

url(r'^list/(?P<letter>[a-z])$', list_view, name="list_view"),

Your view:

def list_view(request, letter=None):
  matches = Anime.objects.all().order_by("title").filter(Q(title__startswith=letter)|Q(title__startswith=letter.upper()))
  return render(request, "your_app/your_template.html", {"matches": matches}
Lomtrur
  • 1,703
  • 2
  • 19
  • 35
0

Still didnt solve the problem after checking this resolutions. I forgot to show how my views.py looks like, and i think the ascii_uppercase is a problem is it true?

from django.shortcuts import render
import string
from home.models import Anime


alphabet = string.ascii_uppercase


def list(request):
    context = {'alphabet': alphabet}
    return render(request, 'list/list.html', context)


def list_detail(request):
    anime = Anime.objects.all().filter(title__startswith=alphabet)
    context = {'anime': anime}
    return render(request, 'list/detail.html', context)
Rafalpero
  • 97
  • 1
  • 2
  • 10
  • just a notice: if you want to clarify your question, you should edit it not adding new answer. returning to your question. string.ascii_uppercase return all Uppercase, instead you should read the target latter from request object e.g. as query string or other. then you should filter the anime objects against that latter as follow: (title__startswith=latterReadFromRequest) – adnanmuttaleb Feb 08 '18 at 08:22