[Django]-How do you dynamically hide form fields in Django?

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

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

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().

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.

Leave a comment