Search code examples
djangodjango-viewsdjango-formsdjango-templatesdjango-class-based-views

How to add context data to Django CreateView when form is valid


Using Django, I have a page with a form that is rendered using CreateView. The success_url is the same url as the original form. When the form is submitted and is valid, I want to insert some data into the context.

I'd like to know the most flexible and clear way to add this context data, because the example below (which works) feels sub-optimal for such a (presumably) common task. I'm looking for a more general solution that using SuccessMessageMixin.

class DemoView(CreateView):
    template_name = "request-demo.html"
    form_class = DemoForm
    success_url = reverse_lazy("base:demo")

    def form_valid(self, form):
        create_and_send_confirmation_email(form)
        return self.render_to_response(self.get_context_data(success_message=True))


Solution

  • Most generically you will define the succcess_url to be the DetailView of the object you have just created. In fact, if you do not define a success_url at all, the default get_success_url will return

    url = self.object.get_absolute_url()
    

    which is commonly the same thing.

    If you want to do something special for a newly created object you might

    1. Redirect to a different URL, such as a subclass of your object DetailView with a custom get_context_data method and/or template name. Or possibly, somewhere completely differerent.
    2. Interrogate the newly created object (in the template and/or get_context_data method) to establish in some application-specific way that it is indeed newly created.