django - 如何在验证前处理/清理字段 [英] django - how to process/clean a field before validation

查看:22
本文介绍了django - 如何在验证前处理/清理字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表格,只有在它被清理后才需要验证.

I have a form that needs to be validated only after it has been cleaned.

运行 form.is_valid() 时会发生什么?是否已清理表单,然后验证已清理的表单版本?

What happens when you run form.is_valid() ? Is the form cleaned and then that cleaned version of the form validated?

我目前得到的行为是,如果我的字段在清理前没有通过验证,即使清理会使其通过,is_valid() 返回 False.

The behaviour I'm getting at the moment, is that if my field does not pass validation before cleaning, even if cleaning would make it pass, is_valid() returns False.

我做错了吗?

# View
class ContactForm(forms.Form):
    message = forms.CharField(widget=forms.Textarea, max_length=5)

    def clean_message(self):
        message = self.cleaned_data['message']
        return message.replace('a', '') # remove all "a"s from message

def contact(request):
    if request.method == 'POST':
        if form.is_valid():
            return HttpResponseRedirect('/contact/on_success/')
        else:
            return HttpResponseRedirect('/contact/on_failure/')

如果消息少于 5 个字符,我希望 form.is_valid() 返回 True NOT 包括 a!

I want form.is_valid() to return True if the message has less than 5 characters NOT including a!

是否可以在 to_python() 之后但在 run_validators() 之前运行 clean_()?还是我应该以其他方式这样做?

Is it possible to run clean_<fieldname>() after to_python() but before run_validators()? Or should I be doing this some other way?

推荐答案

我认为表单验证的过程(及其正确的顺序)真的很有据可查.

I think the process of form validation (and its correct order) is really well documented.

你介意分享你的代码吗?每个表单域都有一个 clean 方法,负责运行 to_pythonvalidaterun_validators(按此顺序).to_python 接受小部件的原始值,将其强制转换为 python 类型,validate 获取被强制转换的值并运行特定于字段的验证.

Would you mind sharing your code? There is a clean method on every formfield, responsible for running to_python, validate and run_validators (in this order). to_python accepts the raw value of the widget, coercing it into a python type, validate takes the coerced value and runs field-specific validation.

关于给定代码的答案已更新

clean_message 在所有其他验证运行后调用,如 to_pythonvalidate 以及最重要的 run_validators>.我认为最后一种方法将检查 max_length 约束没有被违反.因此,您之后更改数据没有任何影响.

clean_message is called after all the other validation has run like to_python, validate and, most importantly, run_validators. I think the last method will check the that the max_length constraint isn't violated. So you changing the data afterwards has no affect.

解决方案是在此处引发 ValidationError.删除 max_length 将避免对输入长度进行任何验证.

The solution is to raise a ValidationError here. Removing max_length will avoid any validation on the input's length.

class ContactForm(forms.Form):
    message = forms.CharField(widget=forms.Textarea)

    def clean_message(self):
        message = self.cleaned_data['message']
        message = message.replace('a', '') # remove all "a"s from message
        if len(message) >= 5:
            raise ValidationError('Too many characters ...')
        return message

这篇关于django - 如何在验证前处理/清理字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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