Django和自定义表单验证

时间:2009-01-28 20:44:29

标签: django forms validation

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

这是我的表单对象

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)

现在我想保持CharField的默认min / max_length检查...但我似乎无法弄清楚如何做到这一点。

如果我将任何代码放入clean()中,则不会检查它们。如果我尝试调用parent.clean()我得到一个错误。

2 个答案:

答案 0 :(得分:27)

如果您只是想清理字段,则无需定义全新字段,您可以在表单的clean_username方法中执行此操作

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-registration进行用户注册,它会在可插拔的应用程序中处理此问题,该应用程序将为您处理所有用户验证,创建和设置。

至于新的firld创建,你的字段的clean()方法应该返回一个清理的值,而不仅仅是打印它。

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

答案 1 :(得分:3)

这在1.0中不起作用......这是我如何解决它

class UsernameField(forms.CharField):
    def clean(self, request, initial=None):
        field = super(UsernameField, self).clean(request)

        from django.contrib.auth.models import User
        user = User(username=request)
        if user is not None:
            raise forms.ValidationError("That username is already taken")