我真的需要你的帮助。我想我已经阅读了所有相关问题的答案,但我无法弄清楚它是如何运作的。
我想从django中的html表单中选择一些属于特定组的用户。
我创建了我的模型"任务",如下所示:
class Task(models.Model):
Taskdetails = models.CharField(max_length=500, null=True)
asset = models.ForeignKey('Asset', null=True)
failure = models.ForeignKey('Failure', null=True)
Created_task_date = models.DateTimeField(default=timezone.now, null=True)
employee = models.ForeignKey("auth.User", null = True)
def __str__(self):
return str(self.id)
django表格是:
class TaskForm (ModelForm):
class Meta:
model = Task
fields = ('Taskdetails', 'asset', 'failure', 'employee',)
观点是:
def task_new(request):
if request.method == "POST":
task_form = TaskForm(request.POST)
subtask_form=SubtaskForm(request.POST)
task_form.employee = User.objects.filter(groups__name='supervisor')
if task_form.is_valid() and subtask_form.is_valid():
task = task_form.save()
subtask = subtask_form.save(commit=False)
task.Created_task_date = timezone.now()
task_form.employee = User.objects.filter(groups__name='supervisor')
task.save()
subtask.task=task
subtask.Created_subtask_date = timezone.now()
subtask.save()
return redirect('great_job')
else:
task_form = TaskForm()
subtask_form = SubtaskForm()
return render(request, 'TaskTrace/task_new.html', {'task_form': task_form, 'subtask_form':subtask_form})
相对的html是
{% block content %}
<div>
<h1>New Task</h1>
<form method="POST" class="task-form">
{% csrf_token %}
Equipment with failure: {{ task_form.asset }}<br><br>
Failure Description: {{ task_form.failure }} <br><br>
Task Details: {{ task_form.Taskdetails }} <br><br>
Employee: {{ task_form.employee }}
<button type="submit" class="save btn btn-default">Open</button>
</form>
</div>
{%endblock%}
我在django-admin 3用户中创建。其中两个属于该组&#34;主管&#34;。我希望在模板中只显示属于此特定组的这两个用户。相反,所有用户都被抛在表单中。
任何人都可以帮助我前进吗?我在这一点上已经坚持了3天。
先谢谢!
答案 0 :(得分:0)
在创建表单时,您需要执行以下操作:
task_form = TaskForm()
task_form.fields["employee"].queryset = User.objects.filter(group__name="supervisor")