嗨(抱歉我的英语不好),我试图用数字输入显示一个表格,而不是在django模型的FK关系中选择,但我无法做到。
问题是我需要在输入框中手动填写产品的ID,但django会自动生成包含所有产品的选择表单!
这就是我在forms.py中所拥有的。
class PurchaseForm(forms.ModelForm):
class Meta:
model = Purchase
fields = [
'date',
'supplier',
'warehouse',
]
widgets = {
'date': forms.DateInput(attrs={
'type': 'date',
}),
}
class PurchaseItemForm(forms.ModelForm):
class Meta:
model = PurchaseItem
fields = [
'product',
'quantity',
'net_purchase_price',
'sell_price',
]
widgets = {
'product': forms.NumberInput(),
}
PurchaseFormSet = inlineformset_factory(
Purchase,
PurchaseItem,
fields='__all__',
extra = 10,
)
这是我的观点
class PruchaseCreateView(CreateView):
template_name = 'purchases/create_purchase.html'
form_class = PurchaseForm
def get_context_data(self, **kwargs):
context = super(PruchaseCreateView, self).get_context_data(**kwargs)
if self.request.POST:
context['formset'] = PurchaseFormSet(self.request.POST)
else:
context['formset'] = PurchaseFormSet()
return context
def form_valid(self, form):
context = self.get_context_data()
formset = context['formset']
if formset.is_valid():
self.object = form.save()
formset.instance = self.object
formset.save()
return redirect(self.object.get_absolute_url())
else:
return self.render_to_response(self.get_context_data(form=form))
我尝试使用小部件NumberInput但没有!任何想法?
答案 0 :(得分:3)
您需要在致电inlineformset_factory
时添加自定义表单:
PurchaseFormSet = inlineformset_factory(
Purchase,
PurchaseItem,
form=PurchaseItemForm
fields='__all__',
extra = 10,
)