Django检查单个字段是否有错误并且没有运行clean()?

时间:2017-12-12 14:00:13

标签: python django

有没有办法检查个人字段是否未通过django的clean()方法验证表单。

我不想手动检查是否有必填字段:

def clean():
    cleaned_data = super().clean()
    half_day = cleaned_data.get('half_day')
    start_date = cleaned_data.get('start_date')
    end_date = cleaned_data.get('end_date')

    if start_date and end_date:
        if half_day:
            if start_date != end_date:
                self.add_error(
                    'half_day',
                    'Start and end date must be the same'    
                )

1 个答案:

答案 0 :(得分:1)

如果start_dateend_date被声明为blank=False, null=False(默认值),那么您可以执行以下操作:

    def clean(self):

        cleaned_data = super(MyModelForm, self).clean()

        if not self.is_valid():
            return cleaned_data

        if cleaned_data.get('half_day'):
            if cleaned_data['start_date'] != cleaned_data['end_date']:
                self.add_error(
                    'half_day',
                    'Start and end date must be the same'    
                )

        return cleaned_data

超级干净会return将请求errors带回#include <stdio.h> #include <stdlib.h> #include <time.h> int main() { srand(time(NULL)); FILE *fp = fopen("myfile.txt", "w"); // open file once at the beginning // in (w)rite mode, not (a)ppend mode if (fp == NULL) { printf("Cannot open file\n"); return 1; // quit if the file cannot be opened } // write the ten numbers for (int i = 0; i < 10; i++) { int x = rand() % 100; fprintf(fp, "%d\n", x); // newline at the end of the lines } fclose(fp); // close file at the end once the numbers have been written return 0; } 模板,您不必处理检查字段是否有值的问题。