以下代码将登录用户分配给对象,如何更改它以将下拉菜单中的选定用户分配给对象?<form method='POST' action="{% url 'post:car' post.id %}"> {% csrf_token %} <label for="select1"></label> <select class="mdb-select md-form" id="select1" onChange="form.submit();"> <option value="" disabled selected>Assign</option> {% for user in current_users %} <option value="{{ user.id }}"> {{ user }} </option> {% endfor %} </select></form>上面的目标是将选定的分配{{user.id}}给{{post.id}}该urls.py是path('post/<int:tag>', views.assigned_post, name='car'),在current_users已经通过注射从已经实现views.py使用 context['current_users'] = ProjectUser.objects.all()该views.py是def assigned_post(request, tag): as_curr = get_object_or_404(Post, id=tag) if request.method == 'POST': if as_curr.assigned_to: as_curr.assigned_to = None as_curr.save() else: as_curr.assigned_to = request.user # < -- Assign to drop down user instead of current user as_curr.save() return HttpResponseRedirect(reverse('post:tasks'))该models.py是class Post(models.Model): assigned_to = models.ForeignKey(ProjectUser, related_name="assigned_user", blank=True, null=True, on_delete=models.CASCADE)我试过的:as_curr.assigned_to = request.POST.get('user_id')但意见正在恢复None的request.POST.get('user_id')
2 回答
杨__羊羊
TA贡献1943条经验 获得超7个赞
因为您的模型将assigned_to 指定为ProjectUser 的ForeignKey,这意味着您必须使用ProjectUser 实例填充它,因此会出现错误。因此,也许可以在保存之前尝试获取 ProjectUser:
# views.py
user = ProjectUser.objects.get(id=request.POST.get('user_id'))
as_curr.assigned_to = user
as_curr.save()
德玛西亚99
TA贡献1770条经验 获得超3个赞
您需要为输入表单元素提供正确的名称,以便从 request.POST 中获取它(例如 name="user_id")
<select name="user_id" class="mdb-select md-form" id="select1" onChange="form.submit();">
添加回答
举报
0/150
提交
取消