Search code examples
pythondjangodjango-tables2

'unicode' object has no attribute '_meta'


I am trying to create a view in which the user selects an option from a drop down menu, submits it, and then some data is returned. Specifically, they will select from models in the database and have returned all of the instances of that class. I am using django-tables2 to output the data so that it is sortable, but this is my sticking point.

Views.py

def output_form(request):
    results = None
    if request.GET.get('browse'):
        selection = request.GET.get('browse')

        class ModelTable(tables.Table):
            class Meta:
                model = selection

        results = ModelTable(selection.objects.all())
        RequestConfig(request, paginate={"per_page": 3}).configure(results)

    return render(request, 'projectdb/output.html', {
        'results': results,
})

HTML

<form method="GET">

    <select name="browse">

        <option>Model1</option>

        <option>Model2</option>

    </select>

    <input type="submit" value="Submit" />

</form><br/><br/>

    {% if results != None %}
        {% render_table results %}
    {% endif %}

The error thrown is as in the title:

'unicode' object has no attribute '_meta'

I have tried converting the 'selection' unicode to a string, which throws basically the same error (str has no attribute _meta).

I would be very grateful for any help.

EDIT: For clarity, what I am trying to achieve:

User selects model from dropdown ---> selected model is passed to the table somehow ---> table is instantiated and returned to the page below the dropdown, with the data from the selected model


Solution

  • model attribute should reference django model class.

    But inside the function output_form, selection reference a request.GET.get('browse'): str object.

    class ModelTable(tables.Table):
        class Meta:
            model = selection # <----
    

    Change the model attribute to correctly reference the model class.

    BTW, extract the ModelTable class definition out of the view function.