当前正在保存表单实例,但当我保存此表单时,未保存填写信息的用户。我想知道如何获取用户并将其添加到新表单对象的创建中。
class ObjectListView(LoginRequiredMixin, FormMixin, ListView):
model = Object
template_name = 'ui/home.html'
context_object_name = 'objects'
form_class = OrderForm
def post(self, request, *args, **kwargs):
form = self.get_form()
if form.is_valid():
form.save()
order_type = form.cleaned_data.get('order_type')
price = form.cleaned_data.get('price')
**user = request.user**
messages.success(request, f'Your order has been placed.')
return redirect('account')
最佳答案
为了在保存表单之前添加更多信息,您可以使用参数commit=False
views.py
class ObjectListView(LoginRequiredMixin, FormMixin, ListView):
...
def post(self, request, *args, **kwargs):
...
if form.is_valid():
obj = form.save(commit=False)
obj.user = request.user ## Assuming that the relevant field is named user, it will save the user accessing the form using request.user
obj.save()
...
return redirect('account') ## this should be indented if it is to work only on successfully saving the form
关于python - 如何在 Django 中基于类的 View 中使用帖子保存表单时保存用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65526094/