我有一个使用 Bootstrap 表单选择的 Django 应用程序。这是从这样的表中填充的:
<div class="div-1 rounded bg-light text-dark ">
{% trans "Active restaurant: " %}
<select class="form-select-sm bg-light text-dark" aria-label={% trans "Select a restaurant" %} id="Selected_Restarurant">
<option selected>{% trans "Select a restaurant" %}</option>
{% for restaurant in restaurants %}
<option value="restaurant.name">{{ restaurant.name }}</option>
{% endfor %}
</select>
</div>
我不知道如何处理用户在上面的表单选择中选择的值。我需要对员工运行过滤器,并更新下面的 home.html 模板中的员工表,以仅显示所选餐厅的员工。我知道这与模型和过滤器有关,这也有详细记录,但是如何找到所选值并根据选择更新下表?:
<table class="table table-sm table-hover">
<thead class="table-success">
<tr>
<!--th scope="col">{% trans "Employees" %}</th-->
<th scope="col">{% trans "Restaurant" %}</th>
<th scope="col">{% trans "First name" %}</th>
<th scope="col">{% trans "Last name" %}</th>
<th scope="col">{% trans "Username" %}</th>
</tr>
</thead>
<tbody class="table-group-divider">
{% for employee in employees %}
{% if employee.restaurant.name == "McDonalds in the bush" %}
<tr>
<!--td>{{ employee.user.first_name }}</td-->
<td>{{ employee.restaurant.name }}</td>
<td>{{ employee.user.first_name }}</td>
<td>{{ employee.user.last_name }}</td>
<td>{{ employee.user.username }}</td>
</tr>
{% endif %}
{% endfor %}
</tbody>
</table>
1)如果列表很大,不建议使用 HTML 加载所有餐厅。 你正在做的是使用 django 模板引擎来构建 html 页面 所以。在这种方法中,我加载 HTML 中的所有餐厅,并使用 java 脚本 jquery 使用像 id 这样的选择器来操作生成的 html。 首先隐藏所有你不想显示的行。稍后,当用户选择一个选项时,只需取消隐藏所需的输出
将此加载到 html 底部
<script>
$('#Selected_Restarurant').change(function () {
var selectedValue = $(this).val();
var restaurntList = [{% for restaurant in restaurants %}
'{{restaurant.name}}',
{%endfor%}];
// Loop through restaurantList to check if selectedValue exists
var found = false;
for (var i = 0; i < restaurantList.length; i++) {
if (selectedValue===restaurantList[i])
{ found=true;
break; }
};
if(found) {
// Show the selected table row
$("#" + selectedValue).show();
// Hide all other table rows
$("tr").not("#"+ selectedValue).hide();
}
else {
// If selectedValue is not found, show all table rows
$("tr").show();
} });
Make sure all the restarurants are loded with id of each restarurants in tr
{% for employee in employees %}
<tr id="{{ employee.restaurant.name }}">
<!--td>{{ employee.user.first_name }}</td-->
<td>{{ employee.restaurant.name }}</td>
<td>{{ employee.user.first_name }}</td>
<td>{{ employee.user.last_name }}</td>
<td>{{ employee.user.username }}</td>
</tr>
{% endfor %}