模型和表单验证之间的区别 [英] Difference between Model and Form validation

查看:81
本文介绍了模型和表单验证之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在处理已经建立的模型,我需要添加一些验证管理. (访问两个字段并检查数据,没有什么太夸张的了)

I'm currently working on a model that has been already built and i need to add some validation managment. (accessing to two fields and checking data, nothing too dramatic)

我想知道在验证角度来看模型和表单之间的确切区别,以及我是否能够像在模型视图中的表单视图中那样,提出一种干净的方法来引发错误?

I was wondering about the exact difference between models and forms at a validation point of view and if i would be able to just make a clean method raising errors as in a formview in a model view ?

  • 为了获得更多知识,为什么要将这两件事分开?

最后,你会怎么做?已经有一些为模型编写的方法,我还不知道是否要重写它以将其变形为表单并简单地添加clean()方法+我不完全知道它们是如何工作的.

And finnaly, what would you do ? There are already some methods written for the model and i don't know yet if i would rewrite it to morph it into a form and simply add the clean() method + i don't exactly know how they work.

哦,一切都在管理界面中,自从我不久前开始使用django以来,它还没有做很多工作.

Oh, and everything is in the admin interface, havn't yet worked a lot on it since i started django not so long ago.

预先感谢

推荐答案

您应使用模型(字段)验证来确保返回的数据类型符合数据库的要求.通常,您不需要它,因为django的内置字段会为您执行此操作,因此,除非您已构建了一些自定义字段或知道自己在做什么,否则不要更改任何内容.

You should use model (field) validation to make sure the returning datatype meets your database's requirements. Usually you won't need this because django's builtin fields do this for you, so unless you've built some custom field or know what you are doing you shouldn't change things.

表单验证是清除用户输入的地方,您可以通过添加clean_FIELD(self)方法为每个表单字段添加一个clean方法,例如

Form validation is where you clean the user's input, you can add a clean method for every form field by adding a clean_FIELD(self) method, e.g.

class ContactForm(forms.Form):
    # Everything as before.
    ...

    def clean_recipients(self):
        data = self.cleaned_data['recipients']
        if "fred@example.com" not in data:
            raise forms.ValidationError("You have forgotten about Fred!")

        # Always return the cleaned data, whether you have changed it or
        # not.
        return data

在运行窗体的主要清理方法之前,它会检查其每个字段的字段级别清理情况

Before a Form's main clean method is ran, it checks for a field level clean for each of its fields

这篇关于模型和表单验证之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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