以下代码将登录用户分配给对象,如何更改它以将下拉菜单中的选定用户分配给对象?
<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
是通过使用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')
答案 0 :(得分:2)
因为您的模型将assigned_to指定为ProjectUser的外键,这意味着您必须使用ProjectUser实例填充它,因此会出现错误。因此,也许在保存之前尝试获取ProjectUser:
# views.py
user = ProjectUser.objects.get(id=request.POST.get('user_id'))
as_curr.assigned_to = user
as_curr.save()
答案 1 :(得分:0)
您需要给输入表单元素正确的名称,以便从request.POST中获取它(例如,name =“ user_id”)
<select name="user_id" class="mdb-select md-form" id="select1" onChange="form.submit();">