Django 发票模型表单集
Posted
技术标签:
【中文标题】Django 发票模型表单集【英文标题】:Django invoice model formset 【发布时间】:2018-09-13 21:53:59 【问题描述】:我正在尝试创建发票表单。我正在尝试使用表单集,因为产品将在销售过程中多次添加。我在创建表单时经常失败。
我的模特:
class Fatura(models.Model):
musteri = models.ForeignKey(CariModel, on_delete=models.CASCADE, blank=False)
fatura_tarihi = models.DateField(auto_now=True, blank=False)
fatura_numarasi = models.CharField(max_length=36, default=fatura_numarasi)
odeme_tarihi = models.DateField(auto_now=False, blank=True)
def __str__(self):
return " - ".format(self.musteri, self.fatura_numarasi)
class FaturaUrunler(models.Model):
fatura = models.ForeignKey(Fatura, on_delete=models.CASCADE, blank=False)
baslik = models.CharField(max_length=128, blank=False)
urun = models.CharField(max_length=128, blank=False)
miktar = models.DecimalField(max_digits=12, decimal_places=3, default=1)
fiyat = models.DecimalField(max_digits=12, decimal_places=3)
vergi = models.CharField(choices=KDV, default=18, max_length=5)
我的观点:
def index(request):
class GerekliFormlar(BaseFormSet):
def __int__(self, *args, **kwargs):
super(GerekliFormlar,self).__init__(*args, **kwargs)
self.queryset = Fatura.object.none()
UrunlerFormset = formset_factory(UrunForm, max_num=0, formset=GerekliFormlar)
if request.method == 'POST':
fatura_form = FaturaForm(request.POST)
urunler_formset = UrunlerFormset(request.POST, request.FILES)
if fatura_form.is_valid() and urunler_formset.is_valid():
fatura = fatura_form.save()
for form in urunler_formset.forms:
urunler = form.save()
urunler.fatura = fatura
urunler.save()
return HttpResponse("tesekkürler")
else:
fatura_form = FaturaForm()
urunler_formset = UrunForm()
c =
'fatura_form': fatura_form,
'urunler_formset': urunler_formset
c.update(csrf(request))
return render_to_response('anasayfa_gecici.html', c)
我想在表格中进行客户选择和产品添加。简单的计费系统
【问题讨论】:
你有urunler_formset = UrunForm()
- 你不想实例化一个表单集吗?
另外,请注意render_to_response
已过时。请改用return render(request, 'anasayfa_gecici.html', c)
,然后您可以删除c.update(csrf(request))
这一行。
@Alasdair "return render (request, 'homepage_gecici.html', c)" 这解决了问题。非常感谢您的帮助。
切换到render
是一个不错的改变,但这并不能解决设置urunler_formset = UrunForm()
的问题,
【参考方案1】:
在您看来,您正在为 GET 请求实例化一个表单 UrunForm()
,为 POST 请求实例化一个表单集 UrunlerFormset()
。在这两种情况下都应该使用UrunlerFormset
。
if request.method == 'POST':
fatura_form = FaturaForm(request.POST)
urunler_formset = UrunlerFormset(request.POST, request.FILES)
...
else:
fatura_form = FaturaForm()
urunler_formset = UrunlerFormset()
【讨论】:
以上是关于Django 发票模型表单集的主要内容,如果未能解决你的问题,请参考以下文章