Python/Django模型覆盖清理的数据

Python/Django模型覆盖清理的数据,python,django,model-view-controller,django-models,django-forms,Python,Django,Model View Controller,Django Models,Django Forms,您好,我目前正在django项目中工作,在我的一个模型中,我有一个文件上载和图像上载,这两个字段的参数都设置为blank=True,但是有一个stipulation,如果这两个字段中的一个不为空,则该字段只能为空,例如,如果imagefield已完成,则用户无需上载文件;如果filefield已完成,则用户无需上载图像 我的问题是我正在努力找出逻辑,这是在管理部分,所以我知道我将有覆盖干净的数据。有人能帮忙吗?您只需要在ModelForm上定义一个自定义的clean()方法,检查是否填充了一个或

您好,我目前正在django项目中工作,在我的一个模型中,我有一个文件上载和图像上载,这两个字段的参数都设置为blank=True,但是有一个stipulation,如果这两个字段中的一个不为空,则该字段只能为空,例如,如果imagefield已完成,则用户无需上载文件;如果filefield已完成,则用户无需上载图像


我的问题是我正在努力找出逻辑,这是在管理部分,所以我知道我将有覆盖干净的数据。有人能帮忙吗?

您只需要在ModelForm上定义一个自定义的clean()方法,检查是否填充了一个或两个字段

def clean(self):
    file_field = self.cleaned_data.get('file_field')
    image_field = self.cleaned_data.get('image_field')

    if file_field and image_field:
        raise forms.ValidationError("You should only provide one of File or Image")
    elif not file_field and not image_field:
        raise forms.ValidationError("You must provide either File or Image")

    return self.cleaned_data

您只需要在ModelForm上定义一个自定义clean()方法,该方法检查是否填充了一个或两个字段

def clean(self):
    file_field = self.cleaned_data.get('file_field')
    image_field = self.cleaned_data.get('image_field')

    if file_field and image_field:
        raise forms.ValidationError("You should only provide one of File or Image")
    elif not file_field and not image_field:
        raise forms.ValidationError("You must provide either File or Image")

    return self.cleaned_data

已完成,即PostComplete中有一个条目已完成,即Post中有一个条目谢谢,尽管我认为我遗漏了,一个文件和一个图像都可以一起上传,我想这会改变条件一些什么?当然,如果,那么只需删除第一个
。谢谢,尽管我认为我遗漏了,一个文件和一个图像都可以一起上传,我想这会改变一些条件什么?当然,如果
,那么只需删除第一个