Django和自定义表单验证 [英] Django and Custom Form validation

查看:118
本文介绍了Django和自定义表单验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个自定义表单域并验证它。这是Django的1.0版本。

I am trying to create a custom form field and validate off it. This is version 1.0 of Django.

这是我的表单对象

class UsernameField(forms.CharField):
    def clean(self, values):
        print ""

这是我称之为

class RegisterForm(forms.Form):
   username = UsernameField(max_length=30, min_length=4)
   password = forms.CharField(widget = forms.PasswordInput(), min_length=5)
   password2 = forms.CharField(widget = forms.PasswordInput(), min_length=5)
   email = forms.EmailField(max_length=75)

现在我想要保持默认的min / max_length检查一个CharField在粘性..但我似乎无法说明如何做到这一点。

Now I want to keep the default min/max_length checks for a CharField in tack.. but I can't seem to figure how how to do that.

如果我把任何代码放在clean()那些没有检查。如果我尝试调用parent.clean()我得到一个错误。

If I put any code into clean() those are not checked. If i try to call parent.clean() i get an error.

推荐答案

如果您只想清理您的字段,则无需定义一个全新的字段,您可以在form的clean_username方法

If you just want to clean your field, there's no need to define a whole new field, you can do that in the form's clean_username method

class RegisterForm(forms.Form):
  username = forms.CharField(max_length=30, min_length=4)
  ...
  ...

  def clean_username(self):
    username = self.cleaned_data['username']
    try:
        user = User.objects.get(username=username)
    except User.DoesNotExist:
        return username
    raise forms.ValidationError(u'%s already exists' % username )

  def clean(self):
    # Here you'd perform the password check
    ...

您还可以考虑使用 django-注册用于Django中的用户注册,它会在可插拔的应用程序中处理,这将是可行的对于您的所有用户验证,创建和设置。

You might also consider using django-registration for user registration in Django, it takes care of this in a pluggable app, which will handle all the user validation, creation and setup for you.

对于新的firld创建,您的字段的clean()方法应该返回一个清除的值,而不仅仅是打印

As for the new firld creation, your field's clean() method should return a cleaned value, not just print it.

class MyField(forms.CharField):
  def clean(self, value):
    # perform cleaning
    return value

这篇关于Django和自定义表单验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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