我是Django / python的新手。我有一个带有依赖项下拉列表的表单。根据您选择的工作区域,工作站的选项将更改,但是有些工作区域没有工作站,在这种情况下,我希望工作站下拉菜单不显示,但我不确定如何要解决这个问题,如果它在html端或另一端
forms.py
class WarehouseForm(AppsModelForm):
"""
Warehouse tracking form fields
"""
class Meta:
model = EmployeeWorkAreaLog
fields = ('adp_number', 'work_area', 'station_number')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['station_number'].queryset = StationNumber.objects.none()
if 'work_area' in self.data:
try:
work_area_id = int(self.data.get('work_area'))
self.fields['station_number'].queryset = StationNumber.objects.filter(work_area_id=work_area_id).order_by('name')
except (ValueError, TypeError):
pass
elif self.instance.pk:
self.fields['station_number'].queryset = self.instance.work_area.stations.order_by('name')
views.py
class EnterExitArea(CreateView):
model = EmployeeWorkAreaLog
template_name = "operations/enter_exit_area.html"
form_class = WarehouseForm
def form_valid(self, form):
emp_num = form.cleaned_data['adp']
area = form.cleaned_data['work_area']
station = form.cleaned_data['station_number']
if 'enter_area' in self.request.POST:
form.save()
return HttpResponseRedirect(self.request.path_info)
elif 'leave_area' in self.request.POST:
form.save()
EmployeeWorkAreaLog.objects.filter(adp_number=emp_num, work_area=area, station_number=station).update(time_out=datetime.now())
return HttpResponseRedirect(self.request.path_info)
def load_stations(request):
work_area_id = request.GET.get('work_area')
stations = StationNumber.objects.filter(work_area_id=work_area_id).order_by('name')
return render(request, 'operations/station_number_dropdown_options.html', {'stations': stations})
这里用户只真正填写他们的#并选择工作区,所以我想知道div中是否有一种方法可以让它显示/消失,如果没有可供选择的选项
enter_exit_area.html
{% extends "base.html" %}
{% block main %}
<form id="warehouseForm" action="" method="POST" data-stations-url="{% url 'operations:ajax_load_stations' %}" novalidate >
{% csrf_token %}
<div>
<div>
{{ form.adp_number.help_text }}
{{ form.adp_number }}
</div>
<div>
{{ form.work_area.help_text }}
{{ form.work_area }}
</div>
<div>
{{ form.station_number.help_text }}
{{ form.station_number }}
</div>
</div>
<div>
<div>
<button type="submit" name="enter_area" value="Enter">Enter Area</button>
<button type="submit" name="leave_area" value="Leave">Leave Area</button>
</div>
</div>
</form>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$("#id_work_area").change(function () {
var url = $("#warehouseForm").attr("data-stations-url");
var workAreaId = $(this).val();
$.ajax({
url: url,
data: {
'work_area': workAreaId
},
success: function (data) {
$("#id_station_number").html(data);
}
});
});
</script>
{% endblock main %}