问题
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
回答1:
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.
回答2:
Perhaps what you want is to translate your selection
from a string to a model class. To do that, use the django.db.models.get_model
function, e.g.:
selected_model = get_model('myapp', selection)
IMHO, defining dynamically your table class as you done does not hurt readability.
来源:https://stackoverflow.com/questions/22162056/unicode-object-has-no-attribute-meta