“已禁用” choiceField的选项-Django [英] "Disabled" option for choiceField - Django
问题描述
我遇到一个简单的问题:
如何在Django框架中通过modelForm和choiceFied生成的下拉菜单中具有一些禁用字段?
I having trouble with a simple question : How to have some "disabled" field in a dropdown menu generated via a modelForm and choiceFied in the django Framework ?
目前,我不知道如何获得这样的输出:
-根1条目-(禁用)
-Elt 1-(未禁用)
-根2输入-(已禁用)
At the moment, I cannot figure out how to obtain such an output : -- Root 1 entry -- (disabled) -- Elt 1 -- (not disabled) -- Root 2 entry -- (disabled)
您有任何建议吗?
Pierre
推荐答案
Django的表单小部件提供了一种传递应在< option>上呈现的属性列表的方法。
标签:
Django's form widgets offer a way to pass a list of attributes that should be rendered on the <option>
tag:
my_choices = ( ('one', 'One'), ('two', 'Two'))
class MyForm(forms.Form):
some_field = forms.ChoiceField(choices=my_choices,
widget=forms.Select(attrs={'disabled':'disabled'}))
不幸的是,这不适用于您,因为该属性将应用于渲染的每个选项标签d。 Django无法自动知道哪些应该启用,哪些应该禁用。
Unfortunately, this won't work for you because the attribute will be applied to EVERY option tag that is rendered. Django has no way to automatically know which should be enabled and which should be disabled.
在您的情况下,我建议编写一个自定义小部件。这很容易做到,而且您没有太多可应用的自定义逻辑。有关此文档,请此处。简而言之:
In your case, I recommend writing a custom widget. It's pretty easy to do, and you don't have that much custom logic to apply. The docs on this are here. In short though:
- 子类
forms.Select
,这是默认的选择渲染器 - 在您的子类中,实现
render(self,name,value,attrs)
方法。使用自定义逻辑来确定值
是否符合需要被禁用的条件。如果需要侵害,请查看django / forms / widgets.py
中render
的简短实现。
- subclass
forms.Select
, which is the default select renderer - in your subclass, implement the
render(self, name, value, attrs)
method. Use your custom logic to determine if thevalue
qualifies as needing to be disabled. Have a look at the very short implementation ofrender
indjango/forms/widgets.py
if you need inspriation.
然后,定义您的表单字段以使用您的自定义小部件:
Then, define your form field to use your custom widget:
class MyForm(forms.Form):
some_field = forms.ChoiceField(choices=my_choices,
widget=MyWidget)
这篇关于“已禁用” choiceField的选项-Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!