Django:创建类似于django admin的内联表单
这已被问过,但没有回答(从我能找到的)。
我有两个模型;
class Invoice(models.Model):
invoice_number = models.CharField(max_length=30)
invoice_date = models.DateField()
class LineItem(models.Model):
description = models.CharField(max_length=50)
unit_price = models.DecimalField(max_digits=9, decimal_places=2)
quantity = models.PositiveSmallIntegerField()
invoice = models.ForeignKey(Invoice)
在django管理界面中,我将LineItem作为Inline to Invoice。 这很有效,因为我想在提高发票的同时添加我的发票订单项。
django应用程序中是否有类似嵌套/内嵌表单的示例模式? 我想向用户展示的视图与管理界面类似,可以在创建发票时输入lineitems。
欣赏任何指导。
我研究了我在这里收到的一些建议,并决定采用@rix建议使用django formsets的稍有不同,但非常符合轨道的解决方案; 基于模型的inlineformset。
我最终为LineItems使用了django inlineformset_factory
,并将Invoice保留为标准ModelForm
。
我的表格;
#forms.py
...
class LineItemForm(ModelForm):
class Meta:
model = LineItem
fields = ['description','unit_price','quantity']
class InvoiceForm(ModelForm):
class Meta:
model = Invoice
fields = ['invoice_date','invoice_number']
我的看法;
#views.py
...
def add_invoice(request):
LineItemFormSet = inlineformset_factory(Invoice, LineItem, form=LineItemForm, extra=5)
if request.method == 'POST':
invoice_form = InvoiceForm(request.POST, prefix='invoice')
lineitem_formset = LineItemFormSet(request.POST, request.FILES, prefix='line')
if invoice_form.is_valid() and lineitem_formset.is_valid():
invoice = invoice_form.save()
# I recreate my lineitem_formset bound to the new invoice instance
lineitem_formset = LineItemFormSet(request.POST, request.FILES, prefix='line', instance=invoice)
# I have to validate (again - so I'm confident) to access clean data
lineitem_formset.is_valid()
lineitem_formset.save()
if 'submit_more' in request.POST:
return HttpResponseRedirect(reverse('invoices:add_invoice'))
else:
return HttpResponseRedirect(reverse('invoices:get_invoices'))
else:
return render(request, 'invoices/invoice_add.html', {
'message' : "Check your form",
'invoice_form' : invoice_form,
'lineitem_formset' : lineitem_formset,
})
else:
invoice_form = InvoiceForm(prefix='invoice')
lineitem_formset = LineItemFormSet(prefix='line')
return render(request, 'invoices/invoice_add.html', {
'invoice_form' : invoice_form,
'lineitem_formset' : lineitem_formset,
})
现在,正如@ tr33hous所建议的那样,我正在玩JS来添加新的内联表单。
我对结果很满意。
但是,我想知道是否有更好的方法,然后创建和验证我的内联formset,以确保它在保存我的发票之前都是有效的,然后重新创建绑定到新发票实例的formset对象,而不是主要开销,但它不会看起来尽可能干净。
我想你可能正在寻找formsets:
https://docs.djangoproject.com/en/dev/topics/forms/formsets/
链接地址: http://www.djcxy.com/p/65431.html