2017-12-13 1 views
0

私はDjango 1.11を使用しています。私はインラインformsetフォームで隠しフィールドに値を追加しようとしています。私はdef get_context_datadef form_validの様々なポイントで隠れフィールド値を挿入しようとして失敗しました。次のように私が使用していたコードは次のとおりです。Djangoは、隠しフィールドインラインフォームセットに値を追加します

views.py

@method_decorator(login_required, name='dispatch') 
class DocumentCreate(CreateView): 
    model = DocumentClient 
    success_url = reverse_lazy('documents') 
    form_class = DocumentForm 

    def get_context_data(self, **kwargs): 
     data = super(DocumentCreate, self).get_context_data(**kwargs) 
     if self.request.POST: 
      data['docform'] = DocumentFormSet(self.request.POST, self.request.FILES) 
     else: 
      data['docform'] = DocumentFormSet() 
     return data 

    def form_valid(self, form): 
     context = self.get_context_data() 
     docform = context['docform'] 
     if docform.is_valid(): 
      self.object = form.save() 
      docform.instance = self.object 
      docform.save() 
      return HttpResponseRedirect('documents') 
     else: 
      return self.render_to_response(self.get_context_data(form=form)) 

forms.py

class DocumentForm(ModelForm): 
    class Meta: 
     model = DocumentClient 
     exclude =() 
     widgets = { 
      'cnum': HiddenInput(), 
     } 

    def __init__(self, *args, **kwargs): 
     super(DocumentForm, self).__init__(*args, **kwargs) 
     for field in self.fields: 
      self.fields['cnum'].required = False 


class DocumentDetailForm(ModelForm): 
    class Meta: 
     model = DocumentDetail 
     exclude =() 
     widgets = { 
      'document_date': DateInput(), 
        } 

    def __init__(self, *args, **kwargs): 
     super(DocumentDetailForm, self).__init__(*args, **kwargs) 
     self.fields['document_description'].required = False 

DocumentFormSet = inlineformset_factory(DocumentClient, DocumentDetail, form=DocumentDetailForm, extra=10, can_delete=False) 

隠しフィールド'cnum'は私が取得するための値を挿入しようとしていますどのようなことですモデル。誰でもこれを達成するための指針を提供することはできますか?どんな支援も感謝しています!

答えて

1

DocumentCreateでは、これを試しましたか?

class DocumentCreate(CreateView): 
    def get_initial(self): 
     # Get initial value from kwargs (If needed) and save as instance variable. 
     self.cnum_val = self.kwargs.get('cnum_value') 

    def form_valid(self, form): 
     # Insert your desired value to cnum (or you can simply forget get_initial and supply whatever value here) 
     form.instance.cnum = self.cnum_val 
     self.object = form.save() 
     ... 
     self.render_to_response(self.get_context_data(form=form)) 

form.instance

hereを見る形で使用される保存されていないモデルオブジェクトを指します。

+0

ありがとうございます!あなたのdef form_valid(self、form):メソッドを使用しました。 – cr1

関連する問題