Search code examples
djangodjango-viewsdjango-generic-views

How to call GenericModelViews with arguments from another view?


I want to return GenericDeleteView with arguments from another view.

I have a view, that gets an pk of an object and I want to delete it using Django generic DeleteView subclass.

The problem is that the pk can be of different Models.

I have the respective GenericDeleteViews defined and if I add them to urls.py and trigger them from there with positional argument, everything works fine. But I would like something little different.

Example of what I would want:

views.py

def delete_object_view(request, pk):
if FirstModel.objects.filter(pk=pk).exists():
    return FirstModelDeteleView.as_view()(request, !!pk!!)
else:
    return SecondModelDeleteView.as_view()(request, !!pk!!)

But the case is that this does not pass the pk to the DeleteView and it returns the error:
Generic delete view must be called with either an object pk or a slug

I tried many alternatives, passing kwargs={'pk':pk} and some other, but nothing seems to be working.

I am desperate and even tough I know some workarounds, this sounds like something that should be possible, and seems elegant.

Thanks for any advice.


Solution

  • I will not follow your approach in calling another view from a view. (i find it is not elegant solution)

    I have not test this answer, so you may need to debug some minor errors later.

    Because your DeleteView may use different Model, then you may want to determine the Model dynamically.

    You still could use the generic DeleteView. Since it uses the SingleObjectMixin, instead of specifying the model in the View, you should then overwrite get_queryset method or get_object method.

    Sample code:

    class MyDeleteView(DeleteView):
        def get_queryset(self):
            if FirstModel.objects.filter(pk=<pk>).exists():
                return FirstModel.objects.all()
            else:
                return SecondModel.objects.all()