好的,所以我实际上是偶然解决了这个,只想了解发生了什么。
我有自己的用户注册表单BaseCreationForm,它扩展了ModelForm并使用UserProfile作为其模型。所有的验证方法都运行良好,但保存方法给了我悲伤。每当我尝试创建一个用户(在视图中创建配置文件,我可能会重构它)时,Django会告诉我“BaseCreationForm对象没有属性清理数据”。
但是,出于沮丧和耗尽的想法,我在save()方法中创建用户之前添加了一个简单的“print self”语句,问题消失了,用户正常创建。下面是一些有效的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()方法:
#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)
答案 0 :(得分:4)
您不应该在form_valid
方法中重新实例化表单。当表单已经有效时调用它,实际上表单将传递给方法。你应该改用它。
(请注意,实际错误是因为您根本没有调用form.is_valid()
,但正如我上面所说,您不应该这样做,因为视图已经在执行此操作。)