我是Django的新手。 我想根据下拉选择显示内容。 在此示例中,我想显示下拉菜单中所选位置的所有车间数据。 是否可以在不重新加载页面的情况下实现该目标?还是必须重新加载页面,重新加载页面后是否可以保留在当前视图上?
谢谢。
我尝试在表单上使用post方法并使用onChange属性。 它成功地重新加载了页面,但是没有显示研讨会的内容,下拉选择返回到默认的'---选择您的位置-',页面返回到顶部。
下面是表格的代码
class LocationForm(forms.Form):
location = forms.ModelChoiceField(label='', queryset=Location.objects.all(), empty_label="--- Choose your location ---",
widget=forms.Select(
attrs={'id': 'ddlLocation', 'name':'ddlLocation', 'class':'selectpicker', 'data-live-search':'true', 'data-size':'5', 'onChange':'frLocation.submit();' }
)
)
下面是该类的代码
class HomeView2(ListView):
template_name = 'myapp/index.html'
def get(self, request):
form_location = LocationForm()
location_id = request.GET.get('location_id')
workshops = Workshop.objects.filter(location_id=location_id).order_by('workshop_name')
args = {'form_location':form_location, 'workshops':workshops}
return render(request, self.template_name, args)
def post(self,request):
form_location = LocationForm()
location_id = request.GET.get('location_id')
workshops = Workshop.objects.filter(location_id=location_id).order_by('workshop_name')
args = {'form_location':form_location, 'workshops':workshops}
return render(request, self.template_name, args)
和index.html
<section class="page-section" id="services">
<div class="container">
<h2 class="text-center mt-0">At Your Service</h2>
<hr class="divider my-4">
<div class="row justify-content-center">
<div class="col-lg-3 col-md-6 text-center">
<div class="mt-5">
<i class="fas fa-4x fa-wrench text-primary mb-4"></i>
<h3 class="h4 mb-2">Select location</h3>
<form id="frLocation" name="frLocation" method="POST">
{% csrf_token %}
{{form_location}}
</form>
</div>
</div>
</div>
<div class="row justify-content-center">
<div class="col-lg-3 col-md-6 text-center">
<div class="mt-5">
<form id="frWorkshop">
{% for workshop in workshops %}
<p>Workshop: {{workshop.workshop_name}}</p>
{% endfor %}
</form>
</div>
</div>
</div>
</div>
</section>