我正在尝试使用Django和HTML从我的数据库填充一个Dropbox。我一直试图弄清楚如何数小时,但它没有更新。
以下是HTML代码:
<select id = "classChoice" >
<option value = "base"> ----- </option>
{% for class.name in objectlist %}
<option value = "class.name"> {{ class.name }} </option>
{% endfor %}
</select>
这是forms.py:
class searchPageForm(forms.Form):
className = forms.ModelChoiceField(queryset= Classroom.objects.all())
studentName = forms.CharField(max_length=120)
studentID = forms.CharField(max_length=20)
这是views.py:
def search(request):
form = searchPageForm()
if request.GET.get('class.name'):
featured_filter = request.GET.get('class.name')
objectlist = searchPageForm.objects.all()
return render(request, 'pollingSite/search.html', {'objectlist': objectlist})
else:
classNames = Classroom.objects.filter(instructor = request.user)
return render(request, 'pollingSite/search.html', locals())
我被困住并且已经尝试过所有事情并且它没有填充。
答案 0 :(得分:1)
In your html page, the {% for object in objectlist %}
means that it will iterate over the objectlist
and assign each object in the list to object
. This means that you can access the attributes of Classroom
using the instance object
. So change the html as follows:
<select id="classChoice">
<option value = "base"> ----- </option>
{% for object in objectlist %} <!-- You were making mistake here -->
<option value = "{{ object.id }}"> {{ object.name }} </option>
{% endfor %}
</select>
And in your forms.py:
class searchPageForm(forms.Form):
className = forms.CharField(max_length=120)
studentName = forms.CharField(max_length=120)
studentID = forms.CharField(max_length=20)