0

如果我将数据库中的布尔字段设置为 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,我不想在表单中显示此字段。

有什么方法可以热吗?

4

1 回答 1

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']
于 2014-09-15T00:08:40.060 回答