Search code examples
djangodjango-class-based-viewsdjango-sessions

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("/")

I would appreciate if someone has a simpler way or another alternative based on using class based views


Solution

  • Class based views that process forms have a method form_valid which is run in case the form is valid. Since you want to write some extra code for that specific case, you should override that method instead of 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