python - 如何在 Django 中基于类的 View 中使用帖子保存表单时保存用户

标签 python django django-views django-forms

当前正在保存表单实例,但当我保存此表单时,未保存填写信息的用户。我想知道如何获取用户并将其添加到新表单对象的创建中。

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/

相关文章:

java - 从 django 运行 java

python - 添加到购物车数量 Django

python - web.py 和 flask

Python:seek(0) 和 open() 本质上是做同样的事情吗?

python - 为什么 django 会在新创建的对象上给我一个 ObjectDoesNotExist 错误?

python - 在Django中的特定时间执行任务

python - 呈现 : 'BoundField' object is not iterable 时捕获类型错误

django - 从 Django View 中的多个表中获取数据

python - 字段内包含引号和逗号字符的 CSV 文件

python - 无法让 Pyglet 渲染