Django如何过滤staff用户并在前端展示列表供普通用户选择?
实现方案
1. 视图层逻辑调整
在渲染对应页面的视图函数中,先查询所有staff身份的用户,通过上下文传递给前端,同时补充表单提交后的存储逻辑:
from django.contrib.auth.models import User from django.shortcuts import render, redirect from .models import DailyFood, PurchaseHistory from django.utils.timezone import now def 你的视图函数名(request): # GET请求渲染页面时传递员工列表 if request.method == "GET": staff_list = User.objects.filter(is_staff=True) return render(request, "你的模板路径.html", {"staff_list": staff_list}) # POST请求处理表单提交 if request.method == "POST": price = request.POST.get("price") staff_id = request.POST.get("staff_id") # 基础参数校验 if not all([price, staff_id, price.isdigit()]): # 可根据业务需求补充错误提示逻辑 return redirect("当前页面路由名") # 写入每日餐费表 DailyFood.objects.create( user_id = staff_id, date = now(), total = int(price) ) # 若需要同步生成消费记录可补充以下逻辑,余额、现金字段根据你的业务规则计算即可 # PurchaseHistory.objects.create( # user_id = staff_id, # date = now(), # balance = 计算后的余额, # hand_cash = 计算后的现金金额 # ) return redirect("提交成功后跳转的路由名")
2. 前端模板修改
把原有标注要展示员工列表的位置替换为下拉选择框即可:
<form action="" method="post"> {% csrf_token %} <div class="modal-body"> <div class="modal-body"> <div class="form-group"> <label>Total price</label> <input type="number" name="price" class="form-control" placeholder="Enter price"> <label>Staff</label> <!-- 员工下拉选择框 --> <select name="staff_id" class="form-control" required> {% for staff in staff_list %} <option value="{{ staff.id }}">{{ staff.username }}</option> {% endfor %} </select> </div> </div> </div> <div class="modal-footer"> <button type="submit" class="btn btn-success">Submit</button> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </form>
补充说明
如果你使用的是自定义User模型,把查询条件里的is_staff替换为你自己定义的员工身份标识字段即可;如果需要展示员工真实姓名而非登录用户名,把模板里的{{ staff.username }}替换为{{ staff.first_name }}或者你自定义的姓名字段即可。
内容的提问来源于stack exchange,提问作者Toufiqur Rahman
相关产品推荐
相关产品推荐

