如果我在数据库中将布尔字段设置为False,我不想在表单中显示字段。
这是我的代码:
class CreateServer(ModelForm):
def __init__(self, g, *args, **kwargs):
super(CreateServer, self).__init__(*args, **kwargs)
if g.boolean_clients:
self.fields['clients'].queryset = Clients.objects.filter(game=g)
else:
# the fields['clients'] shouldn't be displayed in form
pass
...
class Meta:
model = Server
queryset = Server.objects.filter()
fields = ['hostname', 'clients', 'map']
因此,如果g.boolean_clients为true,则必须有过滤器,但如果g.boolean_clients为false,我不想在表单中显示此字段。
有什么方法可以做到吗?
答案 0 :(得分:0)
我还没有对此进行测试,但请尝试:
class CreateServer(ModelForm):
def __init__(self, g, *args, **kwargs):
super(CreateServer, self).__init__(*args, **kwargs)
if g.boolean_clients:
self.fields['clients'].queryset = Clients.objects.filter(game=g)
else:
self.fields.pop('clients')
class Meta:
model = Server
queryset = Server.objects.filter()
fields = ['hostname', 'clients', 'map']