发布数据后,是否有一种通过基于 class 的视图在 django 中创建会话的方法?

Is there a way of creation sessions in django via class based views after posting data?

class CreateCompanyView(CreateView):
    model = Company
    template_name = 'create/company_create.html'
    form_class = CompanyForm
    success_url = '/'

    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST)
        if form.is_valid():
            instance = form.save(commit=False)
            #section where the session is supposed to be created
            request.session['company'] =instance.pk
            instance.save()
        return redirect("/")

如果有人有更简单的方法或基于使用 class 基于视图的其他替代方法,我将不胜感激

基于

Class 处理表单的视图有一个方法 form_valid,如果表单有效,该方法是 运行。由于您想为特定情况编写一些额外的代码,因此您应该覆盖该方法而不是 post:

class CreateCompanyView(CreateView):
    model = Company
    template_name = 'create/company_create.html'
    form_class = CompanyForm
    success_url = '/'
    
    def form_valid(self, form):
        response = super().form_valid(form)
        self.request.session['company'] = self.object.pk # `form_valid` saves the object to the variable `self.object`
        return response