Search code examples
pythondjangodjango-formsdjango-generic-views

Confirming generic FormView POST success back to user with POST data


Using a generic FormView I'd like to reflect something about the POST data that was submitted back to the user, but I'm not sure how best to do this.

class MyView(generic.FormView):
    form_class = MyForm
    def get_success_url(self):
        return reverse('success')

reverse('success') redirects to a simple

class SuccessView(generic.TemplateView):
    template_name = 'success.html'

Is there a way that I can access params object in SuccessView via the get_success_url call, or is there a better (and simpler) way to do this? TIA Dan

UPDATE (my solution, but thanks for the ideas)

I actually found that this was the simplest way (for me) to solve the problem:

class SuccessMixin(object):
    def post(self, request, *args, **kwargs):
        form_class = self.get_form_class()
        form = self.get_form(form_class)

        if form.is_valid():
            return self.form_valid(form)
        else:
            return self.form_invalid(form, **kwargs)

    def form_valid(self, form):
        # this is my post processing step which returns the
        # feedback data that I want to pass to the user
        form_data = form.get_some_data_from_form()
        return render_to_response('submitted.html', 
            {'form_data': form_data,}, 
            context_instance=RequestContext(self.request))

Each view inherits this mixin, and if the form is valid then I pull the feedback data from it and render it as a response - completely bypassing the get_success_url redirect. I've removed the get_success_url and SuccessView.


Solution

  • Include the data as GET parameters in your success url.

    def get_success_url(self):
       url = reverse('success')
       # maybe use urlencode for more complicated parameters
       return "%s?foo=%s" % (url, self.request.POST['bar'])
    

    Then in your template, access the parameters in the GET data.

    foo: {{ request.GET.foo }}