我想使用CreateView在视图中创建并保存一个对象。
> example in django documentation,当我具有字段值(我知道用户和他选择的书)并希望在视图内部创建它时,使用一种形式来创建新对象。
from django.views import generic
class BookReserveView(generic.CreateView):
model = Reservation
person = current_login_user # the user who logged in
book = selected_book # selected book (I have the pk)
success_url = reverse_lazy('book:reserve_book') # when the object saved go to this url
这是我的预订模式。
class Reservation(models.Model):
person = models.ForeignKey(User, on_delete=models.CASCADE)
book = models.ForeignKey(Copy, on_delete=models.CASCADE)
date_reserved = models.DateTimeField(auto_now_add=True)
我尝试了这段代码,并且对我有用。但我喜欢使用通用视图(CBV)
from book.models import Copy,Reservation
def BookReserveView(request,pk):
book = Copy.objects.get(pk=pk)
reserve_obj = Reservation(book=book, person=request.user)
reserve_obj.save()
return HttpResponse(str(reserve_obj))
答案 0 :(得分:0)
您应该在CBV中使用form_valid方法
查看文档-https://docs.djangoproject.com/en/2.0/ref/class-based-views/generic-editing/#form_valid,例如form.instance.user = self.request.user
,以提供您的价值观