Question

I'm trying to pass some extra context to a django CreateView. I have the following url:

url(
    regex = r'^add/(?P<complainant_pk>\d+)/$',
    view = ComplaintCreateView.as_view(),
    name = 'register_complaint',
),

and the view is:

class ComplaintCreateView(PermissionRequiredMixin, CreateView):
    model = Complaint
    form_class = ComplaintForm
    login_url = "/login/"
    permission_required = "complaints.add_complaint"

    def get_context_data(self, **kwargs):
        # Call the base implementation to get a context
        context = super(ComplaintCreateView, self).get_context_data(**kwargs)
        context['complainant'] = Complainant.objects.get(
            pk=self.kwargs['complainant_pk']
        )

This leads to a template error coming from the template line:

{% crispy form %}

saying

VariableDoesNotExist at /complaints/add/6/
Failed lookup for key [form] in...

When I remove the override on get_context_data the form renders fine, but of course then I don't have my extra context. Any ideas what is causing this? I'm totally stumped because the code is identical to some working code elsewhere on my site, excepting the model names. I tried also overriding get_form_class in case the defined form_class was somehow being ignored by my new get_context_data but that didn't help.

Was it helpful?

Solution

I didn't return anything from my overridden method! The answer is therefore to end the get_context_data block with return context.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top