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

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

问题描述



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



我现在得到的行为是,如果我的字段在清理之前未通过验证,即使清洁会使其通过, is_valid()返回 False



我做错了吗?



代码:



  $ :
message = self.cleaned_data ['message']
return message.replace('a','')#从消息中删除所有a

def contact (请求):
如果request.method =='POST':
如果form.is_valid():
返回HttpResponseRedirect('/ contact / on_success /')
否则:
return HttpResponseRedirect('/ contact / on_failure /')

我想要$ code>˚F orm.is_valid()返回 True 如果邮件的小于5个字符包括 a



是否可以运行 clean_< fieldname>() to_python(),但之前 run_validators()?或者我应该这样做一些其他的方式?

解决方案

我认为表单验证的过程(及其正确的顺序)记录良好 http://docs.djangoproject.com/ en / dev / ref / forms / validation /#form-and-field-validation



你介意分享一些代码吗?每个表单上都有一个 clean 方法,负责运行 to_python validate run_validators (按此顺序)。 to_python 接受小部件的原始值,将其强制为python类型, validate 采用强制值并运行字段



关于给定的代码更新了



clean_message 被调用,所有其他验证已经像 to_python 验证,最重要的是, run_validators 。我认为最后一个方法会检查 max_length 约束是否被违反。所以你以后更改数据没有任何影响。



解决方案是在这里提出一个 ValidationError 。删除 max_length 将避免对输入长度进行任何验证。

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

def clean_message(self):
message = self.cleaned_data ['message']
message = message.replace('a','')#从消息
中删除所有a如果len(message)> = 5:
raise ValidationError('Too many字符...')
返回消息


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

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

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.

Am I doing something wrong?

Code:

# 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/')

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

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 good documented. http://docs.djangoproject.com/en/dev/ref/forms/validation/#form-and-field-validation

Would you mind to share some 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.

Answer updated with regards to the code given

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.

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天全站免登陆