我试图使用modelformset_factory
更新模型的多个示例,以渲染出我的模板中的上述示例,每当我填写表格并提交,它不会发布到数据库。
views.py:
def approve(request,pk):
user = User.objects.get(id=pk)
requests = PendingRequest.objects.filter(member=user)
RequestFormset = modelformset_factory(PendingRequest, form=Approve ,extra=0)
if request.method == "POST":
formset = RequestFormset(request.POST, queryset=requests)
if formset.is_valid():
for form in formset:
form.save()
else:
formset = RequestFormset(queryset=requests)
return render(request, "books/approve.html",{"formset":formset, "users":requests})
forms.py:
class Approve(forms.ModelForm):
class Meta:
model = PendingRequest
exclude = ["member", "book_request", "not_approved"]
models.py:
class PendingRequest(models.Model):
book_request = models.ForeignKey(BorrowBook, on_delete=models.CASCADE, null=True)
member = models.ForeignKey(User, on_delete=models.CASCADE, default="", null=True)
book = models.ForeignKey(Books, on_delete=models.CASCADE, default="", null=True)
approved = models.BooleanField(default=False)
not_approved = models.BooleanField(default=False)
approval_date = models.DateTimeField(auto_now=True, null=True)
模板
<body>
<form method="post" action="{% url 'approve' pk=users.0.member.id %}">
{% csrf_token %}
{% for form in formset.management_form %}
{{form}}
{% endfor %}
<table>
<thead>
<tr>
<th>Book Title</th>
<th>Approved</th>
<th>Not Approved</th>
</tr>
</thead>
<tbody>
{% for form in formset %}
<tr>
<td>{{ form.book }}</td>
<td>{{ form.approved }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<button type="submit">Update</button>
</form>
</body>
有什么办法可以修好它吗。
- 我还希望能够在用户未单击模板中的
approved
复选框时将not_approved
字段设置为true。**如有任何关于如何实现此操作的想法,我们将不胜感激
- 我还希望能够在用户未单击模板中的
1条答案
按热度按时间nuypyhwy1#
您应该使用
commit=False
临时保存示例,还应该使用save_m2m()
并将not_approved
字段设置为True
。如果用户没有单击approved复选框,您可以检查表单的cleaned_data中的approved值。尝试以下视图:
**注意:**最好使用
get_object_or_404()
而不是get()
,因为它在给定的模型管理器上调用get()
,但是它引发Http404
而不是模型的DoesNotExist
异常。