Updating context data in FormView form_valid method?

Viewed 31450

I have a class QuestionView which is derived from the FormView class. Here is a code snippet to explain my problem:

class QuestionView(FormView):
    ...
    context_var1 = y

    def form_valid (self, form):
        ...
        self.context_var1 = x
        ...

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

As shown above, I update a set of context variables in form_valid and I intend to use the updated values of these in the template - hence the variables in the context dictionary. The problem with this code is that the change in context_var1 isn't seen - might be because get_context_data is called before the form_valid method. Is there is a workaround for this?

5 Answers

In Django 2.0.1 you can insert context data by overriding either get_context_data or form_invalid.

In your case you could do one of the following overrides:

class QuestionView(FormView):
    ...

    def form_invalid(self, form):
        """If the form is invalid, render the invalid form."""
        return self.render_to_response(
            self.get_context_data(
                form=form, 
                context_key=some_value
            )
        )

Or:

class QuestionView(FormView):
    ...

    def get_context_data(self, **kwargs):
        if 'context_key' not in kwargs:  # set value if not present
            kwargs['context_key'] = some_value
        return super().get_context_data(**kwargs)

Django 2.0.1 inserts under the hood the form into the kwargs of get_context_data.

# File: django.views.generic.edit

class FormMixin(ContextMixin):
    ...

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

    def form_invalid(self, form):
        """If the form is invalid, render the invalid form."""
        return self.render_to_response(self.get_context_data(form=form))

    def get_context_data(self, **kwargs):
        """Insert the form into the context dict."""
        if 'form' not in kwargs:
            kwargs['form'] = self.get_form()
        return super().get_context_data(**kwargs)

Pass plus_context just if save successfull:

class SomeUpdateView(UpdateView):
    ...
    success_url = reverse_lazy('SomeUpdateView')
    plus_context = dict()

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

    def form_valid(self, form, **kwargs):
        self.object.save()
        self.plus_context['pass_to_view_just_after_save_successful'] = 'Save successful!'
        return super(SomeUpdateView, self).form_valid(form)

in template something like:

{% if success %}
<p>{{ success }}</p>
{% endif %}
Related