2016-10-02 106 views
0

在我的模型我的清潔方法限制到只有一個活動的記錄清潔方法不觸發

所以在清潔的方法我只限制一個組合的,其中有效=真每個租賃和is_terminated =假

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' ] 

但是乾淨的方法不再被觸發,它可以防止用戶在同一租約下創建新的recod,其中is_active = true和is_terminated = false 原因是什麼?

+1

我想你需要在覆蓋保存方法時調用它。 http://stackoverflow.com/questions/18803112/django-doesnt-call-model-clean-method在那裏調用'full_clean'。 – Lucas03

+0

是的,好主意謝謝,它的確觸發了它。但現在我得到500錯誤頁面來提高錯誤 –

回答

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 

更好的方法是將清潔移動到某種形式的清潔方法。