python - 如何在 Django 的基于类的视图中使用帖子保存表单时保存用户
问题描述
目前正在保存表单实例,但在我保存此表单时未保存填写信息的用户。我想知道如何抓住用户并将其添加到新表单对象的创建中。
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
视图.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 - 如何处理预测值的变化
- javascript - 模态关闭后如何停止Iframe(视频)?
- php - 为什么 try-catch 不能与 Laravel 5.5 中的 phpseclib 库一起使用?
- ruby-on-rails - Ruby on Rails 5
- python - 无法使用python3在numpy中导入名称'multiarray'
- java - Spring boot Rest 服务消费者应用程序 - Docker 部署的 SSL 问题
- javascript - 在视图上显示通过模型传递的列表
- ios - 快速从 UILocalNotification 迁移到 UNUserNotification
- asp.net - 使用 HttpClient.PostAsync(uri, TParam, MediaFormatter) 时传输编码被分块并且 RequestBody 被编码
- javascript - Javascript RegExp - 测试字符问题