开发者

Help with validation in Models and Forms

I have a few questions about validation in Models and Forms. Could you help me out with these:


Where should validation be done? Should it be in the Model or the Form? Is the right way to go about this is to have validators in the form and constraints in the mode?


What is the difference between writing a 'clean_' method in the form and writing a validator? I've seen that people often put validation checks in the 'clean_' method.


In the request that I'm handling, I have a param in the URL string called 'alive'. This is generally 1 or 0. What would be the correct way of defining this in my form? I need to validate it is a number and can only be 1 or 0. Is this the right way?

alive = models.IntegerField(null=False, max_value=1, min_value=0)

How do I define a default value for this field i.e. if this parameter isn't passed, I default to 0 (False).

I don't have a form on the client side. I'm using the Django form the validate my JS POST request.


In one of model fields I need to store screen resolution in the format 1234x4321. Should I declare this as a CharField add some regular expression validation in both the Model and the Form? Any examples of regular expression validations would开发者_Python百科 be helpful.


Thanks.


The validation should be done on the form, not the model. However, if you are using ModelForms, which is usually makes a lot of sense, it will inherit some of the validation rules from the models themselves (those specific to the database, like maximum_field length, database field type, but also if they can be left blank).

The default value of a field should be passed with its constructor:

form = SomeForm(initial={'alive' : 0})

Although in your case, it appears that if the values that can be obtained are only zero and one, it would be make sense to use a BooleanField instead(tand in that case it would default to false).

In the case of resolutions I would create a mapping between the possible resolution and some arbitrary value.

RESOLUTIONS = (                                                
        ("1","800x600"),
        ("2","1024x768"),                            
         .....                        
)   

and then pass it to the model:

resolutions = models.CharField(RESOLUTIONS, max_length=1)

So that the user gets a select field with the corresponding options and values. On the other hand, if you need the user to insert it him/herself, using two fields (one for width, another for height) would be much easier than validating the user input.

So you can define a method for the model:

def get_resolution(self):
    return "%sx%s" % (self.width, self.height)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜