0
我在Django 1.5.1以下环境:是有可能全部消失从FormField的验证没有覆盖的领域?
forms.py
class UserForm(forms.ModelForm):
class Meta:
model = User
widgets = {
'username': forms.TextInput(attrs={'class': 'input-xlarge', 'placeholder': 'Email Address'}),
'first_name': forms.TextInput(attrs={'class': 'input-xlarge', 'placeholder': 'First Name'}),
'last_name': forms.TextInput(attrs={'class': 'input-xlarge', 'placeholder': 'Last Name'}),
'mobile_phone': forms.TextInput(attrs={'class': 'input-xlarge', 'placeholder': 'Mobile Phone'}),
'office_phone': forms.TextInput(attrs={'class': 'input-xlarge', 'placeholder': 'Office Phone'}),
}
GROUP_CHOICES = [(-1, '[Select]')]
GROUP_CHOICES += [(group.id, group.name.capitalize()) for group in Group.objects.all()]
username = forms.EmailField(
label='Email Address',
required=True,
validators=[validate_email],
widget=forms.TextInput(attrs={'class': 'input-xlarge', 'placeholder': 'Email Address'})
)
password1 = forms.CharField(
label='Password',
widget=forms.PasswordInput(attrs={'class': 'input-xlarge', 'placeholder': 'Password'})
)
password2 = forms.CharField(
label='Password confirmation',
widget=forms.PasswordInput(attrs={'class': 'input-xlarge', 'placeholder': 'Password confirmation'})
)
group = forms.ChoiceField(
label='Group',
choices=GROUP_CHOICES
)
def clean_password2(self):
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 and password2 and password1 != password2:
raise forms.ValidationError('Passwords don\'t match')
return password2
def clean_group(self):
if self.cleaned_data['group'] == '-1':
raise forms.ValidationError('This field is required.')
return self.cleaned_data['group']
def clean_first_name(self):
if self.cleaned_data['first_name'] == '':
raise forms.ValidationError('This field is required.')
return self.cleaned_data['first_name']
def clean_last_name(self):
if self.cleaned_data['last_name'] == '':
raise forms.ValidationError('This field is required.')
return self.cleaned_data['last_name']
def save(self, commit=True):
user = super(UserForm, self).save(commit=False)
user.set_password(self.cleaned_data['password1'])
user.username = self.cleaned_data['username']
if commit:
user.save()
user.groups.clear()
user.groups.add(self.cleaned_data['group'])
user.save()
return user
models.py
class User(auth.models.User):
mobile_phone = models.CharField(
verbose_name='Mobile Phone',
max_length=50
)
office_phone = models.CharField(
verbose_name='Office Phone',
max_length=50
)
我ALTER的* AUTH_USER *让我插入用户名大于30个字符长,所以我可以使用电子邮件作为用户名(我已经尝试过与OneToOneField和自定义模式,这些做法引起了我更多的工作比预期的,所以我不打算采取这种方式)
我的问题:
- 我不得不添加FIRST_NAME和LAST_NAME清洁工因为auth.models.User不具有所需的和小部件对象不允许我设置所需的属性,这是最好的方法吗?
- 我只有一个问题,用户名字段仍然有一个MaxValueValidator最多设置30个。我怎么能消失无它的形式覆盖它。由于我使用的是基于类的视图,当我试图通过UpdateView类更新表单时,覆盖这些字段将不会启动带有模型数据的用户名字段,并将其留空。其余领域没有任何问题
谢谢,抱歉,如果我的英文看起来很丑!
至于点1 [改变字段](http://stackoverflow.com/questions/7682804/django-model-forms-设置必需字段#answer-7683392)可以在类初始化时完成 – 2013-04-20 14:09:19