Maj*_*ati 3 python django validation
我正在使用 django 来填写一些表单,我知道如何使用表单和使用验证,但我的表单很复杂,很难从这些表单创建 Forms 对象。我想知道有没有办法在视图中从 POST 获得的参数上使用验证器?
例如,我有一个名为userthen的字段
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
Run Code Online (Sandbox Code Playgroud)
我知道验证器https://docs.djangoproject.com/en/dev/ref/validators/似乎它们只适用于models和forms。甚至可以验证单个字段吗?如果不是,对于复杂的表格,我还有哪些其他选择?
Validator 只是一个接收表单值的函数,如果该值有效或在无效时引发 ValidationError 则不执行任何操作。
您可以将 Validator 导入您的视图并在那里调用它。
使用名为custom_validate_userthis的验证器可能如下所示:
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
Run Code Online (Sandbox Code Playgroud)
尽管如此 - 如果您有复杂的表单,如果您直接就地处理整个验证,您的视图可能会变得混乱。因此,您通常将此逻辑封装在表单中,或确保在模型级别进行验证。
| 归档时间: |
|
| 查看次数: |
2127 次 |
| 最近记录: |