0
私はDjango 1.11を使用しています。私はインラインformsetフォームで隠しフィールドに値を追加しようとしています。私はdef get_context_data
とdef 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'
は私が取得するための値を挿入しようとしていますどのようなことですモデル。誰でもこれを達成するための指針を提供することはできますか?どんな支援も感謝しています!
ありがとうございます!あなたのdef form_valid(self、form):メソッドを使用しました。 – cr1