我正在做一个项目,允许学生申请从图书馆借书,然后图书管理员决定批准或拒绝请求。
- 型号. py**
class PendingRequest(models.Model):
book_request = models.ForeignKey(Borrow, on_delete=models.CASCADE, null=True)
member = models.ForeignKey(User, on_delete=models.CASCADE, default=None, null=True)
book = models.ForeignKey(Books, on_delete=models.CASCADE, default=None, null=True)
approved = models.BooleanField(default=False)
declined = models.BooleanField(default=False)
approval_date = models.DateTimeField(auto_now=True, null=True)
我使用modelformset_factory
来呈现表单,以更新上述模型的多个示例。我想要实现的是,无论何时图书管理员不批准请求,都能够将declined
字段设置为True,将approved
字段设置为False
- 查看次数. py**
def approve(request, pk):
member = get_object_or_404(User, id=pk)
pending_requests = PendingRequest.objects.filter(member=member)
PendingRequestFormSet = modelformset_factory(
PendingRequest, form=ApproveForm, extra=0
)
if request.method == "POST":
formset = PendingRequestFormSet(request.POST, queryset=pending_requests)
approved = request.POST.get(formset.prefix + "-approved")
if formset.is_valid():
instances = formset.save(commit=False)
for instance in instances:
instance.book_request = instance.book_request
instance.member = instance.member
instance.book = instance.book
instance.save()
else:
formset = PendingRequestFormSet(queryset=pending_requests)
context = {"formset": formset, "member": member}
return render(request, "books/approve.html", context)
- 表格. py**
class ApproveForm(forms.ModelForm):
approved = forms.BooleanField(required=False)
class Meta:
model = PendingRequest
fields = [
"approved",
"book",
]
- 模板**
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Approve Request</title>
</head>
<body>
<h1>Update Pending Requests for {{ member.username }}</h1>
<form method="post">
{% csrf_token %}
{{ formset.management_form }}
<table>
<thead>
<tr>
<th>Book</th>
<th>Approved</th>
</tr>
</thead>
<tbody>
{% for form in formset %}
<tr>
<td>{{form.book}}</td>
<td>{{form.approved}}</td>
</tr>
{% endfor %}
</tbody>
</table>
<input type="submit" value="Update" />
</form>
<style>
select {
appearance: none;
-webkit-appearance: none;
-moz-appearance: none;
background: transparent;
border: none;
font-size: 15px;
}
select {
pointer-events: none;
}
</style>
</body>
</html>
1条答案
按热度按时间pjngdqdw1#
我们的朋友在评论中表示
approved
和declined
字段是互斥的,您只需要其中一个来指示特定的状态。与您的问题相关。表单未验证,因为ID字段是必填字段,因此请将它们添加到:
forms.py
以及www.example.com网站上templates.py
以及www.example.comviews.py
这将设置
approved
字段为True
或False
更新点击。如果你想保持declined
字段然后只需添加到forms.pt
作为一个隐藏字段使用相同的过程,虽然我会建议删除它。