danodonovan
danodonovan

Reputation: 20341

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.

Upvotes: 3

Views: 4648

Answers (3)

Lehrian
Lehrian

Reputation: 343

I was trying to figure this out too and a simple solution is to use:

from django.contrib import messages

In get_success_url(self) you can write

def get_success_url(self)
    messages.add_message(self.request, messages.SUCCESS, 'Contact Successfully Updated!')
    return reverse('contacts:contact_detail', args=(self.get_object().id,))

And in your template you can access this message via

{% for message in messages %}
    {{ message }}
{% endfor %}

Upvotes: 2

Alasdair
Alasdair

Reputation: 308769

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 }}

Upvotes: 5

fourk
fourk

Reputation: 2272

One way to accomplish what you're looking to do would be through the use of Sessions. Store whatever values you need on the user's session object, and access them from within the SuccessView. Check out the Django session documentation for more details.

Upvotes: 1

Related Questions