Home > OS >  Change form based on attribute
Change form based on attribute

Time:12-28

class Client(models.Model):
    name = models.CharField(verbose_name='UID', max_length=80)
    type = models.CharField(verbose_name='Type',
                                choices=BUSINESS_CHOICES,
                                max_length=80,
                                default='b-2')

I have a model like above, what I want to do is based the type attribute need to change the form in update view. I tried the following way in views

class ClientEditView(UpdateView):
    model = Client
    template_name = 'client_edit_form.html'
    success_url = reverse_lazy('xxxx')

    def get_form_class(self):
        if self.object.type == 'b-2':
            form_class = ClientEditForm
        elif self.object.type == 'b-3':
            form_class = ClientEditForm2
        return super(ClientEditView, self).get_form_class() 

But it is throwing error. Using ModelFormMixin (base class of ClientEditView) without the 'fields' attribute is prohibited.

CodePudding user response:

Method get_form_class should return form class. Try this

    def get_form_class(self):
        if self.object.type == 'b-2':
            return ClientEditForm
        elif self.object.type == 'b-3':
            return ClientEditForm2
        return super(ClientEditView, self).get_form_class() 
  • Related