views:

532

answers:

2

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 wan 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)
+2  A: 

You are coding this in the Form. Wouldn't it make more sense to do this using CSS and JavaScript in the template code? Hiding a field is as easy as setting "display='none'" and toggling it back to 'block', say, if you need to display it.

Maybe some context on what the requirement is would clarify this.

hughdbrown
Firstly, just because I think form logic should stay in the form. Also, because I see what fields have already been filled out before and don't show those.
Jason Christa
+1  A: 

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()
Jason Christa