2015-03-30 80 views
0

我想從窗體中隱藏一個模型的字段,這是一個自動提交的時間字段。在django中隱藏模型字段

check_out_time = models.DateTimeField(default = datetime.now() + timedelta(minutes = 60)) 
first_name = models.CharField(max_length = 120) 
last_name = models.CharField(max_length = 120) 

我想在表單中只顯示名字和姓氏,而不是結賬時間。請幫助我,如何隱藏django中的任何字段?

回答

0

https://docs.djangoproject.com/en/1.7/topics/forms/modelforms/#selecting-the-fields-to-use

class YourForm(forms.ModelForm): 

    class Meta: 
     model = YourModel 
     exclude = ('check_out_time',) 

UPDATE:

如果要有條件地排除現場:

class YourForm(forms.ModelForm): 

    def __init__(self, *args, **kwargs):  
     super(YourForm, self).__init__(*args, **kwargs) 
     if <your logic here>: 
      del self.fields['check_out_time'] 

    class Meta: 
     model = YourModel 
+0

感謝,它的工作。我可以在以後根據某些條件包含該字段嗎 – user3887070 2015-03-30 23:45:28

+0

條件排除對我而言不合格。禁止創建沒有'fields'屬性或'exclude'屬性的ModelForm。如果我定義了'__all__',那麼我會在'YourForm' – toscanelli 2016-06-09 11:22:41

+0

中找到錯誤Key'check_out_time'特殊值'__all__'用於指示應該使用* model *中的所有字段。 – mishbah 2016-06-13 10:00:41