2015-09-14 79 views
0

Django get_initial未在表單中填充產品字段。我期待一個下拉菜單,查詢結果在get_initial覆蓋函數中定義。Django get_initial不工作

class PurchaseRequestDetailForm(forms.ModelForm): 
    class Meta: 
     model = PurchaseRequestDetail 
     fields = ["product", "variations", "quantity", "fulfilled", "vat", "discount", "surcharges", "active"] 
     exclude = ("purchase_request",) 


class PurchaseRequestDetailCreateView(CreateView): 
    model = PurchaseRequestDetail 
    form_class = PurchaseRequestDetailForm 
    template_name = "inventory/purchaserequestdetail_form.html" 

    def get_pr_obj(self): 
     pr_id = self.request.session["pr_id"] 
     return PurchaseRequest.objects.get(id=pr_id) 

    def get_initial(self): 
     initial = super(PurchaseRequestDetailCreateView, self).get_initial() 
     try: 
      pr_obj = self.get_pr_obj() 
      initial["product"] = pr_obj.vendor.vendors_products.all() 
     except KeyError: 
      pass 
     self.form_class(initial) 
     return initial 

模板:

<td>{{ form.product|css_class:"form-control" }}</td> 

回答

1

一種簡單的方法來設定ModelChoiceField查詢集是設置字段屬性的形式init();

class PurchaseRequestDetailForm(forms.ModelForm): 
    def __init__(self, *args, **kwargs):  
     # Get initial data passed from the view 
     self.product = None 
     if 'product' in kwargs['initial']: 
      self.product = kwargs['initial'].pop('product') 

     super(PurchaseRequestDetailForm, self).__init__(*args, **kwargs) 
     self.fields['product'].queryset = self.product 

    class Meta: 
     model = PurchaseRequestDetail 
     fields = ["product", "variations", "quantity", "fulfilled", "vat", "discount", "surcharges", "active"] 
     exclude = ("purchase_request",) 

您應該ModelFormMixin勾到get_form_kwargs將數據傳遞到窗體。

class PurchaseRequestDetailCreateView(CreateView): 
    model = PurchaseRequestDetail 
    form_class = PurchaseRequestDetailForm 
    template_name = "inventory/purchaserequestdetail_form.html" 

    def get_pr_obj(self): 
     pr_id = self.request.session["pr_id"] 
     return PurchaseRequest.objects.get(id=pr_id) 

    def get_form_kwargs(self): 
     """ 
     Returns the keyword arguments for instantiating the form. 
     """ 
     kwargs = super(PurchaseRequestDetailCreateView, self).get_form_kwargs() 
     kwargs.update(
      {'initial': 
       {'product': pr_obj.vendor.vendors_products.all()} 
      } 
     ) 
     return kwargs 
+0

這不是多餘的嗎? – tilaprimera

+0

如果kwargs [「initial」]中的「product」拋出KeyError – tilaprimera

+1

@tilaprimera我剛看過'CreateView'並且沒有'get_initial'方法。這可能只屬於'UpdateView'。我會更新我的答案。 –