0

型號:Django表單清潔

class MyModel(models.Model): 
    status = models.ForeignKey(Status, on_delete=models.PROTECT, null=True, blank=True) 
    date = models.DateField() 

形式:

class MyModelForm(ModelForm): 

    class Meta: 
     model = MyModel 
     fields = '__all__' 

    def clean_date(self): 
     cd = self.cleaned_data 
     status = cd.get('status') 
     date = cd.get('date') 

     if not date and status == 1: 
      raise forms.ValidationError((mark_safe('<p class="text-danger">When status is .... You must add date </p>'))) 
     return date 

我清潔功能無法正常工作。怎麼了?你可以幫我嗎 ?

+2

請詳細說明,您的數據和錯誤信息 –

回答

2

如果您是cleaning fields that depend on each other,那麼您應該覆蓋clean方法而不是clean_date

由於status是一個外鍵,它永遠不會等於1。也許你想檢查主鍵,在這種情況下,你應該使用status.pk

def clean(self): 
    cleaned_data = super(ContactForm, self).clean() 
    status = cleaned_data.get('status') 
    date = cleaned_data.get('date') 
    if not date and status.pk == 1: 
     raise forms.ValidationError((mark_safe('<p class="text-danger">When status is .... You must add date </p>'))) 

    return cleaned_data 
+0

謝謝,您的解決方案完美無缺。 – Dominik