Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Change form based on attribute

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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() 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading