Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you dynamically hide form fields in Django?

I am making a profile form in Django. There are a lot of optional extra profile fields but I would only like to show two at a time. How do I hide or remove the fields I do not want to show dynamically?

Here is what I have so far:

class UserProfileForm(forms.ModelForm):
    extra_fields = ('field1', 'field2', 'field3')
    extra_field_total = 2

    class Meta:
        model = UserProfile

    def __init__(self, *args, **kwargs):
        extra_field_count = 0
        for key, field in self.base_fields.iteritems():
            if key in self.extra_fields:
                if extra_field_count < self.extra_field_total:
                    extra_field_count += 1
                else:
                    # do something here to hide or remove field
        super(UserProfileForm, self).__init__(*args, **kwargs)
like image 858
Jason Christa Avatar asked Aug 10 '09 16:08

Jason Christa


People also ask

How to add dynamic fields in form in Django?

To dynamically add field to a form with Python Django, we can add the form with a for loop. to create the MyForm form that has a for loop in the __init__ method that creates CharField s and add them into the self. fields dictionary dynamically. We set the extra argument to a list we get from request.

What is forms ModelForm in Django?

Django Model Form It is a class which is used to create an HTML form by using the Model. It is an efficient way to create a form without writing HTML code. Django automatically does it for us to reduce the application development time.

What is AS_P Django?

as_p() [Django-doc] is a method on a Form . It produces a SafeText object [Django-doc] that contains HTML code to be included in the template.


2 Answers

I think I found my answer.

First I tried:

field.widget = field.hidden_widget

which didn't work.

The correct way happens to be:

field.widget = field.hidden_widget()
like image 125
Jason Christa Avatar answered Oct 27 '22 23:10

Jason Christa


Can also use

def __init__(self, instance, *args, **kwargs):    
    super(FormClass, self).__init__(instance=instance, *args, **kwargs)
    if instance and instance.item:
        del self.fields['field_for_item']
like image 22
oak Avatar answered Oct 27 '22 23:10

oak