Django如何在针对模型的视图中验证请求

时间:2015-09-16 09:53:00

标签: django django-views

在django模型中,有n列和视图中的保存请求,然后如何根据模型验证字段以检查请求是否具有所有必需变量,例如:

models.py

class candidate(models.Model):
   name = models.IntegerField()
   college = models.TextField()
   city = models.TextField()
   state = models.IntegerField(null=True)
   country = models.CharField(max_length=255,null=True)
   phone = models.IntegerField(null=True)

views.py

def save(request):
   try:
     data = json.loads(request.body)
     if 'name' in data and 'college' in data and 'city' in data:
              //do something

这是正确的做法吗?

2 个答案:

答案 0 :(得分:0)

没有。你使用表格。

请参阅documentation on formshow to use them with models

答案 1 :(得分:0)

由于您没有将字段name,college,city标记为可选(即blank = True或null = True),如果缺少这些字段,将自动标记错误。

但是,如果要跨字段执行自定义检查,那么最佳做法是为模型类定义一个干净的方法,并在调用save之前调用它。

class candidate(models.Model):
   name = models.IntegerField()
   college = models.TextField()
   city = models.TextField()
   state = models.IntegerField(null=True)
   country = models.CharField(max_length=255,null=True)
   phone = models.IntegerField(null=True)

   def clean(self):
       if (self.name is None) or (self.college' is None) or (self.city is None):
            raise ValidationError('xxx')

请参阅https://docs.djangoproject.com/en/1.8/ref/models/instances/#validating-objects