[Fixed]-How to access form data in `FormView.get_success_url()`

11👍

You can override form_valid method to write form as instance attribute and use self.form inside get_success_url:

class SelectBoard(generic.FormView):
    form_class = forms.SelectBoard

    def form_valid(self, form):
        """If the form is valid, redirect to the supplied URL."""
        self.form = form    
        return HttpResponseRedirect(self.get_success_url())

    def get_success_url(self):
        board_name = self.form.cleaned_data['name']
        return reverse('leaderboard', board_name=board_name)

0👍

You might set the success_url attribute in form_valid method getting the form field value if it is needed

class SelectBoard(generic.FormView):
    form_class = forms.SelectBoard

    def form_valid(self, form):
        board_name = form.cleaned_data['name']
        self.success_url = reverse('leaderboard', board_name=board_name)

        return super().form_valid(form)

Leave a comment