2011-04-20 43 views
0

forms.py如何訪問modelForms領域,這是因爲模型通過

class BandForm(forms.ModelForm): 
    time_from = forms.ChoiceField(choices=[(8, "08:00"),(9, "09:00"),(10, "10.00"),(11, "11:00"), 
              (12, "12:00"),(13, "13:00"),(14, "14:00"),(15, "15:00"), 
              (16, "16:00"),(17, "17:00"),(18, "18:00"),(19, "19:00"), 
              (20, "20:00"),(21, "21:00"),(22, "22:00"),(23, "23:00")]) 
    time_to = forms.ChoiceField(choices=[(8, "08:00"),(9, "09:00"),(10, "10:00"),(11, "11:00"), 
              (12, "12:00"),(13, "13:00"),(14, "14:00"),(15, "15:00"), 
              (16, "16:00"),(17, "17:00"),(18, "18:00"),(19, "19:00"), 
              (20, "20:00"),(21, "21:00"),(22, "22:00"),(23, "23:00")]) 
    class Meta: 
     model = Entry1 
     exclude = ('created','date') 

部分views.py

if request.method == "POST": 
     form = BandForm(request.POST) 
     if form.is_valid(): 
      form = form.save(commit=False) 
      if year and month and day: 
       form.date = datetime.date(int(year),int(month),int(day)) 
       form.save() 

可以說我想要做一些形式驗證.py for my class Bandform

def clean_fieldname(self): ....

通常你會得到像這樣的參數 - self.cleaned_data.get('field_name')。所以,如果我嘗試獲取self.cleaned_data.get('time_from') - 所有東西都很棒。但是,如果我嘗試獲取self.cleaned_data.get('日期'),我得到None返回。

爲什麼?

回答

Django Modelform (with excluded field) 這是從我提供的帖子有點不清楚,你必須在forms.py訪問實例爲self.instance.fieldname但不self.cleaned_data.get(唯一'字段名')。

+1

因爲它不存在? – 2011-04-20 17:09:21

+0

在models.py我有一個類Entry1與字段日期= models.DateField()。如果我把它auto_now_add = True它自動插入日期,一切正常。如果我在保存表單之前在視圖中插入日期,它怎麼不存在? – Viktor 2011-04-20 17:17:58

回答

0

在你排除:

exclude = ('created','date') 

你將從形式可見不含date領域。這可能解釋了爲什麼您無法訪問cleared_data中的date。嘗試從排除元組中移除date並將其呈現在您的模板中,以查看它是否顯示出來。

+0

確保它以這種方式工作,就像request.POST一樣。但是,如果我不排除日期我得到它的形式,用戶必須填寫,我不想要的。我需要手動設置它,就像你在我看來的那樣。 – Viktor 2011-04-20 22:58:52

+0

現在,我從'排除'字段帶走了日期...我也通過手動設置字段{{form.fieldname}}等等將它排除在模板之外......所以我擺脫了我的模板中的字段問題.. ..但仍感覺像'form.date = datetime.date(int(year),int(month),int(day))'沒有給日期字段賦值,而且我只返回None。 – Viktor 2011-04-20 23:38:10

+0

另外,如果它有幫助...當我嘗試在外殼中填充這樣的形式:'data = {'band_title':'hello','created':datetime.datetime(2011,3,3),'date ':datetime.date(2011,3,3),'time_from':8,'time_to':9}' - 'f = BandForm(data)| f.cleaned_data'我只得到3個參數'{'band_title':u'hello','time_to':u'9','time_from':u'8'}'而不是5。 D – Viktor 2011-04-20 23:58:19