2017-02-09 11 views
1

我嘗試在表單啓動時設置一個字段值。當表單啓動時設置表單值

當我們進入視圖時,這個字段的值被檢索 - 視圖是時間表。然後,對於視圖中設置的每個時間,我想將其關聯回時間表。

@login_required 
@requires_csrf_token 
def timesheet(request, timesheet_id): 
    timesheet = TimeSheet.objects.get(pk=timesheet_id) 
    NewTimeFormSet = modelformset_factory(Time, form=TimeForm, formset=RequiredFormSet) 
    if request.method == 'POST': 
     newtime_formset = NewTimeFormSet(request.POST, request.FILES) 
     for form in newtime_formset: 
      if form.is_valid(): 
       form.save() 

    #then render template etc 

所以,爲了確保窗體驗證我想在表單啓動時設置這個字段。當我在視圖中嘗試在POST後設置此字段時,我無法獲取要設置或驗證的字段。

我的代碼獲取timesheet_id當模型實例在進入視圖

def __init__(self, *args, **kwargs): 
     # this allows it to get the timesheet_id 
     print "initiating a timesheet" 
     super(TimeSheet, self).__init__(*args, **kwargs) 

,然後生成的表單開始,我跑的形式INIT。所以這是我已經試過

class TimeForm(forms.ModelForm): 

    class Meta: 
     model = Time 
     fields = ['project_id', 'date_worked', 'hours', 'description', 'timesheet_id',] 

      # some labels and widgets, the timesheet_id has a hidden input 

    def __init__(self, *args, **kwargs): 
     print "initiating form" 
     super(TimeForm, self).__init__(*args, **kwargs) 
     timesheet = TimeSheet.objects.get(id=timesheet_id) 
     self.fields['timesheet_id'] = timesheet 

這就提出了一個錯誤

NameError: global name 'timesheet_id' is not defined

我不知道如何做到這一點?

我也試圖設置字段在形式爲clean()方法,但它填充(顯示一個打印),然後仍然不驗證,我提出一個formset錯誤'此字段是必需的'。

幫助!

回答

1

您實際上並不接受init方法的形式的timesheet_id參數,因此沒有定義值,因此錯誤。

但是,這是錯誤的方法。沒有必要將價值傳遞給表單,將其作爲隱藏字段輸出,然後將其恢復到原來的狀態。執行此操作的方法是將排除在表格字段中的值,並將其設置爲保存。

class TimeForm(forms.ModelForm): 

    class Meta: 
     model = Time 
     fields = ['project_id', 'date_worked', 'hours', 'description',] 

...

if request.method == 'POST': 
    newtime_formset = NewTimeFormSet(request.POST, request.FILES) 
    if newtime_formset.is_valid(): 
     for form in newtime_formset: 
      new_time = form.save(commit=False) 
      new_time.timesheet_id = 1 # or whatever 
      new_time.save() 

注意,同樣,你應該檢查整個表單集的有效性,通過保存迭代前;否則在遇到無效表單之前,您最終可能會保存其中的一部分。