gpt4 book ai didi

python - Django 验证器函数的返回值存储在哪里?

转载 作者:太空狗 更新时间:2023-10-29 22:24:56 24 4
gpt4 key购买 nike

在我的 django 应用程序中,这是我的 validator.py

from django.core.exceptions import ValidationError
from django.core.validators import URLValidator

def validate_url(value):
url_validator = URLValidator()
url_invalid = False
try:
url_validator(value)
except:
url_invalid = True
try:
value = "http://"+value
url_validator(value)
url_invalid = False
except:
url_invalid = True

if url_invalid:
raise ValidationError("Invalid Data for this field")
return value

用于验证这一点:

from django import forms
from .validators import validate_url
class SubmitUrlForm(forms.Form):
url = forms.CharField(label="Submit URL",validators=[validate_url])

当我输入像 google.co.in 这样的 URL,并在从 validate_url 返回它之前打印值时,它会打印 http://google.co.in但是当我尝试在我的 View 中获取 cleaned_data['url'] 时,它仍然显示 google.co.in。那么我的验证器返回的值去了哪里,我是否需要显式编辑 clean() 函数来更改 url 字段值??

文档说明如下:

The clean() method on a Field subclass is responsible for running to_python(), validate(), and run_validators() in the correct order and propagating their errors. If, at any time, any of the methods raise ValidationError, the validation stops and that error is raised. This method returns the clean data, which is then inserted into the cleaned_data dictionary of the form.

我仍然不确定验证器返回值的去向以及是否可以使用验证器更改 cleaned_data dict。

最佳答案

来自docs :

A validator is merely a callable object or function that takes a value and simply returns nothing if the value is valid or raises a ValidationError if not.

返回值被忽略。

如果您希望能够修改值,您可以在表单上使用 clean_field,如 here 所述:

class SubmitUrlForm(forms.Form):
url = ...
def clean_url(self):
value = self.cleaned_data['url']
...
return updated_value

验证器仅用于验证数据,因此这就是验证器的返回值被忽略的原因。

您正在寻找数据“清理”(将其转换为通用形式)。在 Django 中,Forms 负责数据清洗。

关于python - Django 验证器函数的返回值存储在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43423562/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com