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>
這不是多餘的嗎? – tilaprimera
如果kwargs [「initial」]中的「product」拋出KeyError – tilaprimera
@tilaprimera我剛看過'CreateView'並且沒有'get_initial'方法。這可能只屬於'UpdateView'。我會更新我的答案。 –