20

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)
Jason Christa
  • 12,150
  • 14
  • 58
  • 85

4 Answers4

26

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
  • 12,150
  • 14
  • 58
  • 85
4

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']
oak
  • 137
  • 8
4
def __init__(self, *args, **kwargs):
    is_video = kwargs.pop('is_video')
    is_image = kwargs.pop('is_image')
    super(ContestForm, self).__init__(*args, **kwargs)
    if is_video:
        del self.fields['video_link']
        # self.exclude('video_link')
    if is_image:
        del self.fields['image']

use delete instead of self.exclude().

fedorqui
  • 275,237
  • 103
  • 548
  • 598
Invincible
  • 412
  • 3
  • 19
0

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
  • 47,733
  • 20
  • 85
  • 108
  • 4
    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 Aug 10 '09 at 18:57
  • 1
    This moves business logic into the presentation layer ("these objects don't have this field"). Especially bad if the web developer is NOT the backend developer. – Rob Osborne Aug 14 '12 at 15:04
  • what if a value in a hidden field is not valid (any more)? you'll get "please correct the errors below"...happy searching. – benzkji Aug 28 '20 at 12:17