Milano
Milano

Reputation: 18705

Django admin list_filter - dropdown widget

I can change list_filter of related object to dropdown. The problem is when I want to filter on related objects of related object:

class Match(Model):
    team = models.ForeignKey('Team'...)
    away_team = ... (doesn't matter)

class Team(Model):
    country = models.ForeignKey('Country'...)

When I want to filter Match objects by Team, I do:

list_filter = ['team__country']

To dropdown this filter, I use https://github.com/mrts/django-admin-list-filter-dropdown:

 list_filter[('team',RelatedDropdownFilter)]

When I want to filter Match objects by Country of their Team:

list_filter = ['team__country']

But when I want to make dropdown from this filter, it doesn't work:

list_filter = [('team__country',RelatedDropdownFilter)]

It looks the same as there were not RelatedDropdownFilter specified.

RelatedDropdownFilter

class RelatedDropdownFilter(RelatedFieldListFilter):
    template = 'django_admin_listfilter_dropdown/dropdown_filter.html'

Template

{% load i18n %}
<script type="text/javascript">var go_from_select = function(opt) { window.location = window.location.pathname + opt };</script>
<h3>{% blocktrans with title as filter_title %} By {{ filter_title }} {% endblocktrans %}</h3>
<ul class="admin-filter-{{ title|cut:' ' }}">
{% if choices|slice:"4:" %}
    <li>
    <select style="width: 95%;"
        onchange="go_from_select(this.options[this.selectedIndex].value)">
    {% for choice in choices %}
        <option{% if choice.selected %} selected="selected"{% endif %}
         value="{{ choice.query_string|iriencode }}">{{ choice.display }}</option>
    {% endfor %}
    </select>
    </li>
{% else %}

    {% for choice in choices %}
            <li{% if choice.selected %} class="selected"{% endif %}>
            <a href="{{ choice.query_string|iriencode }}">{{ choice.display }}</a></li>
    {% endfor %}

{% endif %}
</ul>

Do you know what should I do?

Upvotes: 0

Views: 3463

Answers (1)

orokusaki
orokusaki

Reputation: 57118

Your template is checking whether or not there are more than 4 choices:

{% if choices|slice:”4:” %}

My guess is that there are not more than four choices in the test data that you are viewing.

Simply remove that check and always use the <select> in that block, or add more test data. The choices are built based on existing data, rather than simply including all possible values.

Upvotes: 3

Related Questions