Skip to main content
 首页 » 编程设计

python之在不使用表单或模型的情况下验证 django 中的单个字段

2024年09月07日32daizhj

我正在使用 django 填写一些表单,我知道如何使用表单和验证,但我的表单很复杂,很难从这些表单创建表单对象。我想知道有什么方法可以对从 View 中的 POST 获取的参数使用验证器吗?

例如我有一个名为user then

def login_view(request): 
    # if this is a POST request we need to process the form data 
    if request.method == 'POST': 
        user=request.POST["user"] 
        # check whether it's valid without using forms 

我了解验证器 https://docs.djangoproject.com/en/dev/ref/validators/而且它们似乎只适用于 models 和 forms。甚至可以验证单个字段吗?如果不是,对于复杂表单我还有哪些其他选择?

请您参考如下方法:

Validator 只是一个函数,它接收表单值,如果值有效则不执行任何操作,或者在无效时引发 ValidationError。

您只需将验证器导入您的 View 并在那里调用它即可。

使用名为 custom_validate_user 的验证器,这可能看起来像这样:

def login_view(request): 
    # if this is a POST request we need to process the form data 
    if request.method == 'POST': 
        user=request.POST["user"] 
        try: 
            custom_validate_user(user) 
        except ValidationError as e: 
            # handle the validation error 

然而 - 如果您有复杂的表单,如果您直接就地处理整个验证,您的 View 可能会变得困惑。因此,您通常将此逻辑封装在表单中,或确保在模型级别进行验证。