我正在尝试创建自定义表单字段并验证它.这是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()我得到一个错误.
如果你只想清理你的字段,就不需要定义一个全新的字段,你可以在表单的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