django模型中的清洁方法未触发

时间:2016-10-02 17:44:32

标签: django

在我的模型中,我的clean方法限制为只有一个活动记录

因此,在clean方法中,我只为每个租约限制一个组合,其中active = True且is_terminated = false

 class LeaseTerm(CommonInfo):
        version = IntegerVersionField( )
        start_period = models.ForeignKey(Period, related_name='start_period' )
        end_period = models.ForeignKey(Period, related_name='end_period')
        lease = models.ForeignKey(Lease)
        increase  = models.DecimalField(max_digits=7, decimal_places=2)
        amount  = models.DecimalField(max_digits=7, decimal_places=2)
        is_terminated = models.BooleanField(default=False)


        def clean(self):
                model = self.__class__
                if self.lease_id and (self.is_terminated == False) and model.objects.filter(lease=self.lease, is_active=True ).exclude(id=self.id).count() > 0:
                    raise ValidationError('!Lease has a active Term , terminate existing term  prior to creation of a new one'.format(self.lease))

这是创建新术语

的观点
def term_new(request,pk,uri):
    lease = get_object_or_404(Lease, pk=pk)
    title = 'term'
    uri = _get_redirect_url(request, uri)
    if request.method == "POST":
        form = LeaseTermForm(request.POST)
        form.lease = lease
        if form.is_valid():
            term = form.save(commit=False)  
            #term.lease = lease      
            term.save()
            messages.add_message(request, messages.SUCCESS, str(term.id) + "-SUCCESS Object created sucssefully")


            return redirect(uri)
    else:
        form = LeaseTermForm()
    return render(request, 'object_edit.html', {'form': form, 'title': title, 'extend': EXTEND})

形式

class LeaseTermForm(forms.ModelForm):
    class Meta:
        model = LeaseTerm
        fields = [  'amount',
        'start_period','end_period', 'increase','is_terminated' ]  

然而,不再触发clean方法,它会阻止用户使用is_active = true和is_terminated = false在相同的租约下创建新的recods 可能是什么原因?

1 个答案:

答案 0 :(得分:2)

我认为form.is_valid()方法不会调用模型clean方法,但会清除表单字段,然后尝试保存它。在保存期间会出现错误,因为您自己没有处理它,所以会引发错误。修复它的一种(非常糟糕的)方法是:

def term_new(request,pk,uri):
    lease = get_object_or_404(Lease, pk=pk)
    title = 'term'
    uri = _get_redirect_url(request, uri)
    if request.method == "POST":
        form = LeaseTermForm(request.POST)
        form.lease = lease
        if form.is_valid():
            term = form.save(commit=False)  
            #term.lease = lease  
            try:    
                term.save()
            except ValidationError:
                pass # Handle returning errors

更好的方法是将清洁工具移至表格清洁方法之一。