clean()方法在模型和字段验证 [英] clean() method in model and field validation

查看:103
本文介绍了clean()方法在模型和字段验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型的 clean()方法和基本字段验证的问题。这是我的模型和 clean()方法。

  class Trial model.Model):

trial_start = DurationField()
movement_start = DurationField()
trial_stop = DurationField()


def clean (self):
from django.core.exceptions import ValidationError
if not(self.movement_start> = self.trial_start):
raise ValidationError('movement start must be> = trial开始')
如果没有(self.trial_stop> = self.movement_start):
raise ValidationError('try stop必须是> = move start')
如果没有(self.trial_stop > self.trial_start):
raise ValidationError('试用停止必须是>试用开始)

我的 clean()方法检查某些值是否在正确的范围内。如果用户忘记填写一个字段,例如 move_start ,然后我收到一个错误:



无法将datetime.timedelta与没有类型



我很惊讶,因为原来的 clean()函数应该捕获缺少的条目(所有 movement_start 是必填字段)。那么如何才能对缺少的值进行基本检查,我的自定义检查值是否在一定范围内?这可以通过模型的 clean()方法完成,还是需要使用 Forms



EDIT1 使其更加清晰: trial_start movement_start trial_stop 都是必填字段。我需要写一个 clean()方法,该方法首先检查所有三个字段是否被填写,然后检查这些值是否在一定范围内。 >

以下代码例如不工作,因为 trial_start 可能为空。我想避免检查每个字段的存在 - django应该为我做这个。

  class TrialForm(ModelForm) :

class Meta:
model =试用

def clean_movement_start(self):
movement_start = self.cleaned_data [movement_start]
test_start = self.cleaned_data [trial_start]
如果没有(movement_start> = trial_start):
raise forms.ValidationError('movement start must be> = trial start')
return self.cleaned_data [move_start]

EDIT2 想要将这个检查添加到模型的 clean()方法是在python shell上创建的对象将自动检查正确的值。表单对于视图是很好的,但是我还需要对shell进行值检查。

解决方案

我想这是去:

  class TrialForm(ModelForm):

class Meta:
model =

def clean(self):

data = self.cleaned_data
如果没有(data.keys()中的'moving_start'和数据中的'trial_start'。 key.keys()中的keys()和'trial_stop')
raise forms.ValidationError(请填写缺少的字段)

trial_start = data ['trial_start']
movement_start = data ['movement_start']
trial_stop = data ['trial_stop']
$ b如果没有(movement_start> = trial_start):
raise forms.ValidationError '运动开始必须是> =试用开始')

如果没有(trial_stop> = movement_start):
raise forms.ValidationError('trial stop m ust be> =运动开始')

如果没有(trial_stop> test_start):
raise forms.ValidationError('trial stop must be> trial start')

返回数据

编辑这种方法的缺点是,只有通过表单创建对象,该值检查才有效。在python shell上创建的对象将不被检查。


I have a problem with a model's clean() method and basic field validation. here's my model and the clean() method.

class Trial(models.Model):

    trial_start = DurationField()
    movement_start = DurationField()
    trial_stop = DurationField()


    def clean(self):
        from django.core.exceptions import ValidationError
        if not (self.movement_start >= self.trial_start):
            raise ValidationError('movement start must be >= trial start')
        if not (self.trial_stop >= self.movement_start):
            raise ValidationError('trial stop must be >= movement start')
        if not (self.trial_stop > self.trial_start):
            raise ValidationError('trial stop must be > trial start')

My clean() method checks whether certain values are in the correct range. If the user forget to fill out a field, e.g. movement_start, then I get an error:

can't compare datetime.timedelta to NoneType

I'm surprised that I get this error, since the original clean() function should be catching that missing entry (after all movement_start is a required field). So how can I the basic checking for missing values, and my custom check whether values are in certain ranges? Can this be done with model's clean() method, or do I need to use Forms?

EDIT1 to make it more clear: trial_start, movement_start and trial_stop are all required fields. I need to write a clean() method which first checks that all three fields have been filled out, and then, check whether the values are in a certain range.

The following code for example DOES NOT work, since trial_start might be empty. I want to avoid having to check for the existence of each field - django should do that for me.

class TrialForm(ModelForm):

    class Meta:
        model = Trial

    def clean_movement_start(self):
        movement_start = self.cleaned_data["movement_start"]
        trial_start = self.cleaned_data["trial_start"]
        if not (movement_start >= trial_start):
            raise forms.ValidationError('movement start must be >= trial start')
        return self.cleaned_data["movement_start"] 

EDIT2 The reason that I wanted to add this check to the model's clean() method is that objects that are created on the python shell, will automatically be checked for correct values. A form will be fine for views, but I need the value check also for the shell.

解决方案

I guess that's the way to go:

class TrialForm(ModelForm):

    class Meta:
        model = Trial

    def clean(self):

        data = self.cleaned_data
        if not ('movement_start' in data.keys() and 'trial_start' in data.keys()  and 'trial_stop' in data.keys()):
            raise forms.ValidationError("Please fill out missing fields.")

        trial_start = data['trial_start']
        movement_start = data['movement_start']
        trial_stop = data['trial_stop']

        if not (movement_start >= trial_start):
            raise forms.ValidationError('movement start must be >= trial start')

        if not (trial_stop >= movement_start):
            raise forms.ValidationError('trial stop must be >= movement start')

        if not (trial_stop > trial_start):
            raise forms.ValidationError('trial stop must be > trial start')

        return data

EDIT the downside of this approach is, that value checking will only work if I create objects through the form. Objects that are created on the python shell won't be checked.

这篇关于clean()方法在模型和字段验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆