EarlyCoder
EarlyCoder

Reputation: 1313

Django DetailView and get request

I have a detail view with a drop-down list. The user can choose an item in the drop-down list and the information about that item should appear below it. This requires that the DetailView includes something like this:

def get_context_data(self, **kwargs):
    context = super(InvoiceDetail, self).dispatch(*args, **kwargs)
    request = self.request

    if request.GET:
        try:
            invoice_selector = request.GET.get('invoice_selector', None)
            invoice = Invoice.objects.get(id = int(invoice_selector) ) # either a string representing a number or 'add invoice'
            context_object_model = invoice
        except ValueError:
            return HttpResponseRedirect(reverse('accounting:add_invoice'))

    return context

How do I over-write the context_object_model? The above code does not make the change.

Upvotes: 1

Views: 726

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599956

This is not something you should do in get_context_data. You should check for "add invoice" in the get method, and do the rest in get_object.

class MyDetailView(DetailView):
    ...
    def get(self, request, *args, **kwargs):
        self.invoice_selector = request.GET.get('invoice_selector')
        if self.invoice_selector = 'add invoice':
            return HttpResponseRedirect(reverse('accounting:add_invoice'))
        return super().get(request, *args, **kwargs)

    def get_object(self):
        if self.invoice_selector:
            obj = self.model.objects.get(pk=self.invoice_selector)
        else:
            obj = super().get_object()

        return obj

Upvotes: 2

Related Questions