How do you dynamically hide form fields in Django?

断了今生、忘了曾经 提交于 2020-01-01 02:25:48

问题


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)

回答1:


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



回答2:


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']



回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/1255976/how-do-you-dynamically-hide-form-fields-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!