Nirav Patel
Nirav Patel

Reputation: 1327

i want to display only selected year data in Django

Here i put my code file so you can get idea about my code

In my index.html

{% load tag %}

<body>

<select name="select_year">
<option>2017</option>
<option>2018</option>
<option>2019</option>
<option>2020</option>
</select>
</br>
</br>

<table border="1">
    <tr>
        <td>No</td>
        <td>Name</td>
        <td>DOB</td>
        <td>Year</td>
    </tr>

    {% for Manvi_User in ordering %}

    <tr>
        <td>{{forloop.counter}}</td>
        <td>{{ Manvi_User.first_name }}</td>
        <td>{{ Manvi_User.dob}}</td>
        <td>{{year|calculate_year:forloop.counter0}}</td>
    </tr>


    {% endfor %}
</table>

</body>

in vies.py

def index(request):
    all_user = Manvi_User.objects.all()
    ordering = all_user.order_by('dob')

    return render(request, 'index.html', {'ordering': ordering})

in tag.py

@register.filter
def calculate_year(year, loop_counter):
    try:
        year = int(2017)
    except ValueError:
        return None
    else:
        return str(year + (loop_counter // 2))

in year i put static year using tag.py

if user select 2019 i want to display only data who have year 2019

Upvotes: 1

Views: 242

Answers (1)

bonidjukic
bonidjukic

Reputation: 1479

As far as I understand what you're trying to do here, which is to filter the queryset depending on the year selected - the way you started is not really the way to do it.

You should look into django-filter app which makes it pretty easy to accomplish what you're trying here.

For this specific situation, you'd have to define your custom filter within filters.py, and then use that filter in your view.

Upvotes: 1

Related Questions