我有以下表格和模型:
class Book(models.Model):
name = models.CharField(max_length=128, null=True, blank=True)
author = models.CharField(max_length=128, null=True, blank=True)
borrower = models.ForeignKey('core.User')
class BookForm(forms.ModelForm)
class Meta:
model = Book
fields = ("name", "author", "borrower")
@login_required
def private(request):
if request.method == 'POST':
form = BookForm(request.POST)
if form.is_valid():
book = form.save(commit=False)
book.save()
else:
form = BookForm()
return render(request, 'borrow.html', {'form': form, })
在我的网站上,用户可以借书。每本书都有自己的借书人。
问题是字段“借款人”被翻译成html select,我想将其隐藏并将其设置为当前登录的用户。
我将不胜感激实现此目标
答案 0 :(得分:0)
从fields
列表中删除借方,并在您的视图中进行设置:
if form.is_valid():
book = form.save(commit=False)
book.borrower = request.user
book.save()