python 如何在 Django 中动态隐藏表单字段?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/1255976/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you dynamically hide form fields in Django?
提问by Jason Christa
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?
我正在 Django 中制作个人资料表单。有很多可选的额外配置文件字段,但我只想一次显示两个。如何隐藏或删除不想动态显示的字段?
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)
回答by Jason Christa
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()
回答by oak
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']
回答by Invincible
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 deleteinstead of self.exclude().
使用delete代替self.exclude().
回答by hughdbrown
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.
您正在表单中对此进行编码。在模板代码中使用 CSS 和 JavaScript 这样做不是更有意义吗?隐藏字段就像设置“display='none'”并将其切换回“block”一样简单,例如,如果您需要显示它。
Maybe some context on what the requirement is would clarify this.
也许关于要求是什么的一些背景会澄清这一点。

