如何在Django中动态隐藏表单字段? [英] How do you dynamically hide form fields in Django?
本文介绍了如何在Django中动态隐藏表单字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我迄今为止所做的:
class UserProfileForm form.ModelForm):
extra_fields =('field1','field2','field3')
extra_field_total = 2
class Meta:
model = UserProfile
def __init __(self,* args,** kwargs):
extra_field_count = 0
用于键,self.base_fields.iteritems()中的字段:
如果键在self.extra_fields中:
如果extra_field_count< self.extra_field_total:
extra_field_count + = 1
else:
#在此处隐藏或删除字段
super(UserProfileForm,self).__ init __(* args,** kwargs )
解决方案
我想我找到了我的答案。 >
首先我试过:
field.widget = field.hidden_widget
没有工作。
正确的方式恰好是:
field.widget = field.hidden_widget()
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)
解决方案
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()
这篇关于如何在Django中动态隐藏表单字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文