好的,所以我实际上是偶然解决了这个问题,只是想了解发生了什么。
我有自己的用户注册表单 BaseCreationForm,它扩展了 ModelForm 并使用 UserProfile 作为其模型。所有的验证方法都运行良好,但保存方法让我很伤心。每当我尝试创建用户时(配置文件是在视图中创建的,我可能会重构它),Django 会告诉我“BaseCreationForm 对象没有属性清理数据”。
但是,当出于沮丧和想法耗尽时,我在 save() 方法中创建用户之前添加了一个简单的“打印自我”语句,问题消失了,用户正在正常创建。下面是几个可用的 clean() 方法,save() 方法和视图中调用 clean() 和 save() 方法的片段。
clean() 方法正常工作
#example clean methods, both work beautifully
def clean_email(self):
email = self.cleaned_data["email"]
if not email:
raise forms.ValidationError(self.error_messages['no_email'])
try:
User.objects.get(email=email)
except User.DoesNotExist:
return email
raise forms.ValidationError(self.error_messages['duplicate_email'])
def clean_password2(self):
# Check that the two password entries match
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError(
self.error_messages['password_mismatch'])
return password2
保存()方法:
#save method requiring wizardry
def save(self, commit=True):
#This line makes it work. When commented, the error appears
print self
###
user = User.objects.create_user(
username=self.cleaned_data.get("username"),
first_name=self.cleaned_data["first_name"],
last_name=self.cleaned_data["last_name"],
email=self.cleaned_data["email"],
)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
和视图(一些东西被遗漏了):
class RegistrationView(FormView):
template_name = 'register.html'
form_class = BaseCreationForm
model = UserProfile
success_url = '/account/login/'
def form_valid(self, form):
form = BaseCreationForm(self.request.POST,
self.request.FILES)
user = form.save()
profile = user.get_profile()
profile.user_type = form.cleaned_data['user_type']
profile.title = form.cleaned_data['title']
profile.company_name = form.cleaned_data['company_name']
.
.
.
profile.save()
return super(RegistrationView, self).form_valid(form)