是否有办法让按钮执行以下操作?当用户按下按钮时,它会获取当前用户的user.username
,并自动从models.py
填写BookInstance
表格,然后将其保存到数据库中。
从models.py
开始:
class BookInstance(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
book = models.ForeignKey("Book", on_delete=models.RESTRICT, null=True)
imprint = models.CharField(max_length=200, blank=True, null=True)
due_back = models.DateField(blank=True, null=True)
borrower = models.ForeignKey(
User, on_delete=models.SET_NULL, blank=True, null=True)
LOAN_STATUS = (
('m', 'Maintenance'),
('o', 'On Loan'),
('a', 'Available'),
('r', 'Reserved')
)
status = models.CharField(
max_length=1, choices=LOAN_STATUS, blank=True, default='a')
class Meta:
ordering = ['due_back']
def __str__(self):
return f'{self.id} - {self.book.title}'
def get_absolute_url(self):
return reverse("catalog:book_list")
class Book(models.Model):
title = models.CharField(max_length=50)
author = models.ForeignKey(
'Author', on_delete=models.SET_NULL, null=True)
summary = models.TextField(
max_length=500, help_text="Enter brief description")
isbn = models.CharField('ISBN', max_length=13, unique=True)
genre = models.ManyToManyField(Genre, help_text="Select genre")
language = models.ForeignKey(
"Language", on_delete=models.SET_NULL, null=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("catalog:book_detail", kwargs={"pk": self.pk})
这是我从我的views.py
:
def borrowBook(request, pk):
context = {
'book_instance': BookInstance.objects.all()
}
success_url = reverse_lazy('catalog:index')
if request.method == "POST":
form = BorrowForm(request.POST or None)
if form.is_valid():
book_instance.id = BookInstance.objects.get(pk=pk)
book_instance.book = BookInstance.objects.get(book=book)
book_instance.borrower = request.user
book_instance.status = 'o'
book_borrowed_count = BookInstance.objects.filter(
owner=request.user).count()
if book_borrowed_count < 4:
book_instance = form.save(commit=False)
book_instance.save()
else:
print("Maximum limit reached!")
return redirect('catalog:index')
return render(request, 'catalog/book_detail.html', {'form': form})
下面是我forms.py
中的BorrowForm
:
class BorrowForm(forms.ModelForm):
class Meta:
model = BookInstance
fields = '__all__'
下面是我urls.py
中的:
path("book_list/book/<int:pk>/borrow", views.borrowBook, name="borrowBook"),
我还尝试在这里使用CBV:
class BorrowBookView(PermissionRequiredMixin, CreateView):
permission_required = 'login'
model = BookInstance
fields = '__all__'
template_name = 'catalog/borrow_form.html'
success_url = reverse_lazy('catalog:index')
def post(self, request, *args, **kwargs):
book_instance.id = BookInstance.objects.get(pk=pk)
book_instance.book = BookInstance.objects.get(book=book)
book_instance.borrower = request.user
book_instance.status = 'o'
book_instance = form.save(commit=False)
book_instance.save()
来自urls.py
的CBV路径:
path("book_list/book/<int:pk>/borrow/",
views.BorrowBookView.as_view(), name="book_borrow"),
下面是我如何使用这里的建议来实现这个按钮:
<form action="#" method="post">
{% csrf_token %}
<button
type="submit"
class="btn btn-dark flex-shrink-0 "
value="{{ book.id }}">Borrow
</button>
但当我按下它似乎并没有保存任何东西到数据库,只是弹出错误,虽然我可能会实现按钮或功能,从我的是错误的意见.感谢和赞赏提供的任何帮助.
1条答案
按热度按时间bvjxkvbb1#
你不需要一个
Django form
来完成这个任务。表单通常用于创建对象或编辑它的字段(比如在管理页面)。这里user
不是编辑或创建对象(书),而是借用一个。所以基本上,我们只需要列出所有可用的图书示例
(status='a')
,并有一个按钮来“借用”它,借用操作是将status
更新为'r'
或'o'
,并将借用者更新为当前的user
,LoginRequiredMixin
保证request
对象中存在该user
views.py
borrow_book.html
urls.py