JavaCake
JavaCake

Reputation: 4115

How to pass context data in success_url?

I have made a form where i wish to return to the same form again, this time with context data that can be used in my template to show that the form has been successfully sent.

How can i do this?

class ContactUsView(FormView):
    form_class = ContactUsForm
    template_name = 'website/pages/contact_us.html'

    def form_valid(self, form):
        form.send_email()
        return super(ContactUsView, self).form_valid(form)

    def get_success_url(self):
        # Something here?

So basically i want get_success_url to return to the ContactUsView with e.g. {'success':'true'} which i can read in the template and render a box that says it has been successfull. I dont want to change to another static page!

Upvotes: 8

Views: 6884

Answers (2)

djvg
djvg

Reputation: 14255

The success_url approach uses a redirect, which implies you need to pass any additional context data as url parameters, as described in hasan-ramezani's answer.

An alternative would be not to use success_url at all:

Instead, you could override form_valid() so it returns a TemplateResponse instead of an HTTPResponseRedirect, following the example of form_invalid(). Something similar is described here.

This way, there is no need to modify your urls.py.

For example:

class ContactUsView(FormView):
    form_class = ContactUsForm
    template_name = 'website/pages/contact_us.html'

    def form_valid(self, form):
        """Render the form again, with current form data and custom context."""
        context = self.get_context_data(form=form)
        context['success'] = True
        context['whatever'] = 'some other custom context'
        return self.render_to_response(context=context)

Upvotes: 3

Hasan Ramezani
Hasan Ramezani

Reputation: 5194

add a url like this to urls.py:

url(r'^contact/(?P<success>\w+)$', ContactUsView.as_view(), name="ContactUsView"),

And you can access to this parameter in class-based view like this:

add get_context_data method to your class-view

class ContactUsView(DetailView):
    context_object_name = 'my_var'

    def get_context_data(self, **kwargs):
        context = super(ContactUsView, self).get_context_data(**kwargs)
        context['success'] = self.success
        return context

And you can use {{ my_var.success }} in your template.

Upvotes: 4

Related Questions