Django使用多对多关系使用表单更新字段

时间:2019-02-12 23:45:54

标签: python django python-3.x django-forms django-views

我有两个处于多对多关系的模型。我想使用一种表格来更新字段,当授权者可以选择拒绝或批准休假时,该表格具有一个删除列表。休假获得批准后,我希望能够调整Leave_current_balance。但是,我收到错误消息:从代码行current_balance.save()

中,'float'对象没有属性'save'。

def unitDirectorForm(request,id):
    if request.method=='POST':
     
        getstaffid=NewLeave.objects.get(id=id)
        form = DirectorForm(request.POST, instance=getstaffid)
        if form.is_valid():
            form.save()
            total_days = getstaffid.Total_working_days
            current_balance = getstaffid.user.leave_balance.Leave_current_balance
            diff_balance = current_balance - total_days
            current_balance = diff_balance
            current_balance.save()
            return HttpResponse('You have successfuly Authorise the leave')

    else:
        
        form=DirectorForm()
        balance_form = leavebbalanceForm()

    return render(request,'managerauthorisedform.html',{'form':form})
    
                                                  
    
class LeaveBalance(models.Model):
    user=models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True,)
    Leave_current_balance= models.FloatField(null=True, blank=True, default=None)
    Year=models.CharField(max_length=100,default='')
    def __unicode__(self):
             return  self.Year


class NewLeave(models.Model):
      user=models.ForeignKey(User,default='',on_delete=models.CASCADE)
   leave_balance=models.ManyToManyField(Leave_Balance)
    Leave_type=models.CharField(max_length=100,blank=False,default='')
    Total_working_days=models.FloatField(null=True,  blank=False)
    leave=(
        ('annual','annual'),
        ('sick','sick'),

    )

  Leave_type=models.CharField(max_length=100,choices=leave,blank=False,default='')
    def __unicode__(self):
        return  self.Leave_type

class DirectorForm(forms.ModelForm):
    class Meta:
        model=NewLeave
        fields=('Director_Authorization_Status','Authorized_by_Director','Date_Authorized',)
        widgets={
            'Date_Authorized':DateInput()
        }

1 个答案:

答案 0 :(得分:0)

因此,首先,我不知道您的form是什么样子,但我会猜测。首先,发生错误是因为您试图在类型为save的变量上调用float函数。您应该保存表格,而不是数字。在调用total_days...之前,您需要完成从current_balance = diff...行到form.save()行的所有计算。完成这些计算后,应将current_balance分配给form.fields['Leave_current_balance'],然后保存表格。