models.py
class KEBReading(models.Model):
#id = models.AutoField(primary_key=True,db_column='kr_id')
date=models.DateField()
time=models.TimeField()
truepower_reading=models.DecimalField(max_digits=6,
decimal_places=2,blank=False,null=False)
apparentpower_reading=models.DecimalField(max_digits=6,
decimal_places=2,blank=False,null=False)
truepower_consumed=models.DecimalField(max_digits=6, decimal_places=2)
voltage_reading=models.IntegerField(blank=False,null=False)
powerfactor=models.DecimalField(max_digits=3,decimal_places=2)
forms.py
class KEBReading_form(forms.ModelForm):
class Meta:
model=KEBReading
exclude=("truepower_consumed","powerfactor")
widgets = {
"date" : forms.widgets.DateInput(format="%d/%m/%Y"),
"time" : forms.widgets.TimeInput(format="%H:%M")
}
views.py
def KEBReading1(request):
if request.method == "POST":
form = KEBReading_form(request.POST)
if form.is_valid():
prevdate=KEBReading.objects.latest("date")
print prevdate.date
print prevdate.time
# q1 = KEBReading.objects.get(datetime.date.today()-datetime.timedelta(0))
kr_truepower_reading = form.cleaned_data["truepower_reading"]
kr_apparentpower_reading = form.cleaned_data["apparentpower_reading"]
truepower_consumed1=kr_truepower_reading-prevdate.truepower_reading
powerfactor1=kr_truepower_reading- prevdate.truepower_reading/(kr_apparentpower_reading-prevdate.apparentpower_reading)
form.save()
KEBReading.objects.filter().values("date","time","truepower_reading",
"apparentpower_reading","truepower_consumed","voltage","powerfactor")
q2=KEBReading.objects.latest("date")
context={'KEBReading_form':form,'q2':q2}
return render_to_response('keb.html',context,context_instance=RequestContext(request))
else:
form = KEBReading_form()
return render_to_response('keb.html',{'KEBReading_form':form},context_instance=RequestContext(request))
我想在数据库中保存truepower_consumed aftr计算。但它给我一个错误truepower_consumed列不能为null。我已经在表格中排除了truepower_consumed。但在数据库中我需要保存该字段
答案 0 :(得分:2)
您需要使用commit=False
保存表单并为所需字段指定适当的值并再次保存对象。
示例:
def KEBReading1(request):
if request.method == "POST":
....
#your code till save
obj = form.save(commit=False)
#assing your values
obj.truepower_consumed = truepower_consumed1
obj.powerfactor = powerfactor1
obj.save() #save
的更多详情
答案 1 :(得分:2)
您应该使用form.save(commit=False)
代替form.save()
,然后计算剩下的两个字段。
请查看以下代码框架:
## replace form.save() with following lines
obj = form.save(commit=False)
## Assign values to those 2 fields after calculation
## you can add a method on your model to do this
obj.calculate()
## those two values were assigned after call to calculate
## now you can save your obj
obj.save()
## Method to be added in your model
def calculate(self):
## Calculate truepower_consumed
## Calculate powerfactor
self.truepower_consumed = <calculated truepower consumed>
self.powerfactor = <calculated power factor>