我是django的新手,我想制作一个简单的会计应用程序,但是我面临以下问题: 我有3个模型;帐户,日记帐和journalLine, 我希望每个日记帐编号可以有多行,例如日记帐编号1可以有4行,依此类推。 因此,在提交之前,我希望自动创建新的日记帐编号,并将值分配给外键字段(jounralNumber),而不显示列表(列表仅显示在数据库上创建的日记帐编号)
models.py
from django.db import models
from django import forms
# Create your models here.
# Model For chart of accounts table
class accounts(models.Model):
accNumber = models.AutoField(primary_key=True,unique=True)
accName = models.CharField(max_length=200,unique=True)
accNumberMin = models.PositiveIntegerField(default=0,unique=True)
accNumberMax = models.PositiveIntegerField(default=0,unique=True)
#-- to definde values for choices main or sub-account-start
main = 'main'
sub = 'sub'
main_sub_choices = ((main, 'Main account'),(sub, 'Sub account'))
#-- to definde values for choices for main or sub-account-end
main_sub =
models.CharField(max_length=10,choices=main_sub_choices,default='sub')
def __str__(self): ## to show accounts as names not objects in Admen panel
return self.accName
class journal(models.Model):
journalNumber = models.PositiveIntegerField(default='',unique=True)
journalDate = models.DateField()
journalDesc = models.CharField(max_length=300)
def __str__(self):
return str(self.journalNumber)
class journalLine(models.Model):
LineNumber = models.AutoField(primary_key=True)
journalNumber = models.ForeignKey(journal,on_delete=models.CASCADE)
accNumber =
models.ForeignKey('accounts',on_delete=models.CASCADE,blank=False)
debit = models.PositiveIntegerField(default=0)
credit = models.PositiveIntegerField(default=0)
def __str__(self):
return str(self.LineNumber)
views.py
def postpage(request):
initial = {'journalNumber': journal.objects.all().count() + 1,}
lineformset = modelformset_factory(journalLine,exclude=(),extra=1)
if request.method == 'POST':
form = journalForm(request.POST)
lineform = lineformset(request.POST)
if lineform.is_valid():
lineform.save()
form.save()
return HttpResponseRedirect('/myacc/thanks/')
else:
form = journalForm(initial=initial)
lineform = lineformset(queryset=journalLine.objects.all().none())
return render(request,'myacc/post.html',{'form':form, 'lineform':lineform})
答案 0 :(得分:0)
我的建议是先保存日记帐,然后再保存带有设置为该日记帐的journal_number的日记帐行。您所看到的将是这样,
def postpage(request):
initial = {'journalNumber': journal.objects.all().count() + 1,}
lineformset = modelformset_factory(journalLine,exclude=(),extra=1)
if request.method == 'POST':
form = journalForm(request.POST)
if form.is_valid():
journal = form.save()
lineform = lineformset(request.POST)
if lineform.is_valid():
lineform.save(commit=False)
lineform.journal_number = journal # or journal.pk
lineform.save()
return HttpResponseRedirect('/myacc/thanks/')
else:
form = journalForm(initial=initial)
lineform = lineformset(queryset=journalLine.objects.all().none())
return render(request,'myacc/post.html',{'form':form, 'lineform':lineform})
希望这会有所帮助!
编辑:这样,您必须将journal_number字段排除在外。如果要保留日记帐编号字段,则需要将表单分为两个步骤,一个步骤创建日记帐,另一个步骤创建journal_line。