增:
def add_users(request): if request.method == "POST": user_id = request.POST.getlist("add_user") text_users = request.POST.get("text_users") text_pwd = request.POST.get("text_pwd") new_id = models.User.objects.create(name=text_users, pwd=text_pwd) new_id.roles.add(*user_id) # 多对多字段添加方法 return redirect("/users/") add_obj = models.Role.objects.all() return render(request, "add_users.html", locals())
删:
def delete_users(request, id): models.User.objects.filter(id=id).delete() return redirect("/users/")
改:
def edeit_users(request, id): if request.method =="POST": user_id = request.POST.getlist("add_user") text_users = request.POST.get("text_users") text_pwd = request.POST.get("text_pwd") update_obj = models.User.objects.get(id=id) update_obj.name=text_users update_obj.pwd=text_pwd # 多对多用set update_obj.roles.set(user_id) update_obj.save() return redirect("/users/") user_text = models.User.objects.filter(id=id) roles_list = user_text.values_list("roles__id") roles_list_new = [] for i in roles_list: roles_list_new.append(i[0]) role_list = models.Role.objects.all() id = id return render(request, "edeit_users.html", locals())
查:
def users(request): user_list = models.User.objects.all() return render(request, "user.html", locals())