将request.user保存到django额外视图。
该示例来自Django-Extra-Views。似乎是作为例子说明的。
https://django-extra-views.readthedocs.org/en/latest/views.html
class OrderCreateView(CreateWithInlinesView):
model = Order
inlines = [ItemsInline, TagsInline]
def get_success_url(self):
return self.object.get_absolute_url()
以下尝试过。它们不起作用。
def form_valid(self, form):
# self.object = form.save()
form.instance.owner = self.request.user
form.save()
return super(OrderCreateView, self).form_valid(form)
throws error:
IntegrityError at /add/
null value in column "owner_id" violates not-null constraint
还尝试添加form.save
def save(self, commit=True):
instance = super(OrderCreateView, self).save(commit=False)
instance.owner = self.request.user
instance.save()
throws
'OrderForm' object has no attribute 'request'
答案 0 :(得分:0)
如果有人遇到此问题,我可以通过在视图中添加以下内容来使其工作。
def forms_valid(self, form, inlines):
form.instance.owner = self.request.user
return super(CreateView, self).forms_valid(form, inlines)