Search code examples
pythondjangodjango-viewsdjango-class-based-views

How to pass user submitted form data into the success_url in django


I am trying to pass the user submitted form data into the url kwargs. As of now I am directely returning the redirect response within the form_valid methoad of django's class based views.

class BillsSelectMonthView(GetFormKwargsMixin, FormView):
    form_class = SelectMonthAndCustomerForm
    template_name = 'customers/bills_select_month.html'
    success_url = reverse_lazy('customers:bills_select_month')
    current_page_name = PAGE_NAME_BILLS

    def form_valid(self, form):
        month_year = form.cleaned_data['month']
        self.customer = form.cleaned_data['customer']
        return redirect(
            'customers:bills_preview', 
            month= int(month_year.month), 
            year = int(month_year.year), 
            customer_id = int(self.customer.pk))

But, with this approach some of the django's other internal methoad will be skipped. I am just wondering is there any other or better way to do the same.

Thanks.


Solution

  • You should override get_success_url() method for this:

    def get_success_url(self):
        return reverse(
            "customers:bills_preview", kwargs={"month": self.month, ...}
        )
    

    Just save the needed values for get_success_url() in form_valid().