Search code examples
htmldjangodjango-templatesdjango-filterdjango-filters

ValueError at /plants/plants/ too many values to unpack (expected 2) when using django_filters


Hej!

I'm having trouble with my django filter. When I put {{myFilter}} in the template I only get an ObjectNumber and when I put {{myFilter.form}} I get the error:

ValueError at /plants/plants/

too many values to unpack (expected 2)

Does anyone have an idea what's going on?

# views.py

def plants_view(request):
    plants = Plant.objects.all()

    myFilter = PlantFilter(plants)

    context = {"plants": plants, "myFilter": myFilter}

    return render(request, 'plants/search_table.html', context)

# filters.py

class PlantFilter(django_filters.FilterSet):
    class Meta:
        model = Plant
        fields = ['name',]

it doesn't matter if I use fields = [ ] or fields = '__all__' .

template.html

{% extends "landing/base.html" %}
{% load static %}
{% load i18n %}
{% load admin_urls %}
{% block page-title %} {%translate "View Plants" %} {% endblock %}
{% block head %}
<link href="{% static 'landing/vendor/tabulator/dist/css/tabulator.min.css' %}" rel="stylesheet">
<link href="{% static 'landing/vendor/tabulator/dist/css/bootstrap/tabulator_bootstrap4.min.css' %}" rel="stylesheet">
{% endblock %}

{% block content %}

        <br>
        <div class="row">
            <div class="col">
                <div class="card card-body">

                    <form method="get">
                        {{myFilter.form}}

                        <button class="btn-primary" type="submit">Search</button>
                    </form>

                </div>
            </div>
        </div>
        </br>

# models.py
class Plant(models.Model):
    name = models.CharField(
        max_length=200
    )
    
    def __str__(self):
        return f"{self.name}"

    def serialize(self):
        return {
            "Name": self.name
    }

Solution

  • Did you follow the documentation on this page ?

    views.py

    def plants_view(request):
        plants = Plant.objects.all()
    
        myFilter = PlantFilter(request.GET, queryset=plants)
    
        context = {"plants": plants, "myFilter": myFilter}
    
        return render(request, 'plants/search_table.html', context)
    

    template.html

    <form method="get">
        {{ myFilter.form.as_p }}
        <button class="btn-primary" type="submit">Search</button>
    </form>