2017-02-09 2 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 후이 필드를 설정하려고하면 유효성을 검사하도록 설정하거나 양식을 가져올 수 없습니다. 모델 인스턴스가보기

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

그리고 형태가 생성 입력에서 시작하고 난 형태를 초기화를 실행할 때

내 코드는 timesheet_id을 가져옵니다. 그래서 내가이 내가이 작업을 수행하는 방법을 모르는

NameError: global name 'timesheet_id' is not defined

이 ...

나는 또한 설정을 시도 한 오류가 발생

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 

시도한 것입니다 필드를 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() 

참고, 다시, 당신은 저장할을 반복하기 전에 전체의 formset의 유효성을 확인해야합니다; 그렇지 않으면 잘못된 양식이 발생하기 전에 그 중 일부를 저장하게 될 수도 있습니다.

관련 문제