2017-08-03 63 views
0

我有一個inlineformset_factory如何填充inlineformsets在Django

CoinInfoFormSet = forms.inlineformset_factory(Portfolio,CoinInfo 
       ,form = CoinForm,can_delete=False,extra=1) 

產生我inlineformset。但是,當我嘗試在我的updateview中填充它時,數據沒有綁定,併產生錯誤:「(隱藏的字段組合)內聯外鍵與父實例主鍵不匹配。」

class UpdatePortFolio(LoginRequiredMixin,UpdateView): 
    model = Portfolio 
    fields = ('title','is_public') 
    template_name = 'hello/edit_create_portfolio.html' 

    def post(self, request, *args, **kwargs): 
     portfolioForm = PortfolioForm(data=request.POST) 
     self.object = portfolioForm.save(commit=False) 
     data = self.get_context_data() 
     if 'add_coin' in request.POST: 
      cp = request.POST.copy() 
      cp['coininfo_set-TOTAL_FORMS'] = int(cp.get('coininfo_set-TOTAL_FORMS')) + 1 
      data['CoinInfoFormSet'] = CoinInfoFormSet(cp, prefix='coininfo_set') 
     for form in data['CoinInfoFormSet']: 
      print(form,'\n\n') 
     return render(request, 'hello/edit_create_portfolio.html', data) 


    def get_context_data(self, **kwargs): 
     data = super(UpdatePortFolio, self).get_context_data(**kwargs) 
     print(self.get_object()) 
     portfolio = self.get_object() 

     if self.request.POST: 
      data['CoinInfoFormSet'] = CoinInfoFormSet(instance=portfolio, prefix='coininfo_set') 
     else: 
      data['CoinInfoFormSet'] = CoinInfoFormSet(instance=portfolio, prefix='coininfo_set') 
     return data 

我應該如何填充我的inlineformset?

回答

0

問題是您沒有爲CoinInfoFormSet()指定實例。您需要鏈接CoinInfoFormSet對象與窗體。即獲取您嘗試更新的投資組合或幣的ID,並將其指定爲CoinInfoFormSet的實例。

+0

實例不是問題,因爲self.get_object()是Portfolio的一個實例。此外,當我呈現他們工作的內聯表格。但是我不能發佈他們,因爲他們沒有約束。 –