首页 > 解决方案 > 如何在 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')

标签: pythondjangodjango-viewsdjango-forms

解决方案


为了在保存表单之前添加更多信息,您可以使用参数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

推荐阅读