2014-09-13 52 views
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是真實的,必須有過濾器,但如果g.boolean_clients是假的,我不希望在表單中顯示此字段。

有沒有什麼辦法可以做到這一點?

回答

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'] 
相關問題