0

In generic UpdateView, if you need to dynamically change the form depending on the passed object you can use this function (as in this answer):

def get_form_class(self):
    if self.object.pk == 1:
        return MyForm
    else:
        return OtherForm

Is there a similar function if I want to change the model? where model is:

class SomeUpdateView(generic.UpdateView):

    login_required = True
    template_name = '...'
    model = SomeModel ## I need it to be dynamic
    form_class = SomeForm 
    success_url = reverse_lazy('some_url')
Alasdair
  • 298,606
  • 55
  • 578
  • 516
Mike Vlad
  • 351
  • 1
  • 4
  • 12
  • This question can help you to override the get_queryset [link](https://stackoverflow.com/questions/19707237/use-get-queryset-method-or-set-queryset-variable) – Italo Lemos May 24 '18 at 12:23

2 Answers2

3

As described in documentation for ModelFormMixin.model you can dynamically compute the queryset your view will work on by overriding get_queryset():

def get_queryset(self):

    if any_condition:
        return MyModel.objects.filter(type='foo')
    elif another_condition:
        return AnotherModel.objects.all()
    else:
        return MyModel.objects.all()

There is a terrific website to quickly retrieve all attributes of Django class based views. I don't think i'm allowed to advertise here, but you can access it from ccbv.co.uk (I'm not the creator of this website, nor related to it, but I use it almost everyday...).

Antwane
  • 20,760
  • 7
  • 51
  • 84
1

There isn't a get_model method you can override.

Instead, you can override get_queryset, and return a queryset of the model you want to use.

def get_queryset(self):
    if use_my_model():
        return MyModel.objects.all()
    else:
        return OtherModel.objects.all()

Or you can override get_object, and return the object of the model you want to use.

def get_object(self):
    if use_my_model():
        return get_object_or_404(MyModel, pk=self.kwargs['pk'])
    else:
         return get_object_or_404(OtherModel, pk=self.kwargs['pk'])
Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • The override worked, thx. I'll try to dig in more so i can understand better but it did work very good. – Mike Vlad May 24 '18 at 12:51