在我的webapp中,我想使用其电子邮件地址自动设置Django用户的用户名字段。目前我在调用我的表单的 is_valid()方法之前在视图中执行此操作。但我不应该在表单的 clean()方法中进行操作吗?
我的表格:
from django.contrib.auth.forms import UserCreationForm
class DjangoUserCreateForm(UserCreationForm):
required_css_class = 'required-field'
def __init__(self, *args, **kwargs):
super(DjangoUserCreateForm, self).__init__(*args, **kwargs)
# Making fields required
self.fields['first_name'].required = True
self.fields['last_name'].required = True
self.fields['email'].required = True
self.fields['password1'].required = True
self.fields['password2'].required = True
class Meta:
model = DjangoUser
fields = ['first_name', 'last_name', 'email', 'password1', 'password2']
以下是观点:
class MyView(TemplateView):
...
def post(self, request, *args, **kwargs):
user_form = DjangoUserForm(request.POST)
if user_form.is_valid():
user = user_form.save(commit=False)
# In our system the email is also the username
user.username = user_form.cleaned_data['email']
user.save()
...