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)
                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.
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.
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.
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()
                        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']
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With