好吧,我实际上是偶然解决了这个问题,只是想了解发生了什么。
我有自己的用户注册表单 BaseCreationForm,它扩展了 ModelForm 并使用 UserProfile 作为其模型。所有的验证方法都工作正常,但保存方法让我很伤心。每当我尝试创建用户时(配置文件是在 View 中创建的,我可能会重构它),Django 会告诉我“BaseCreationForm 对象没有属性清理数据”。
但是,当出于挫败感和想法用尽时,我在 save() 方法中创建用户之前添加了一个简单的“print self”语句,问题消失了,用户正在正常创建。下面是几个有效的 clean() 方法,save() 方法和调用 clean() 和 save() 方法的 View 中的片段。
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
和 View (遗漏了一些东西):
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)
最佳答案
您不应该在 form_valid
方法中重新实例化表单。当表单已经有效时调用它,并且确实将表单传递到方法中。您应该改用它。
(请注意,实际错误是因为您根本没有调用 form.is_valid()
,但正如我在上面所说的,您不应该调用,因为 View 已经在执行此操作。)
关于python - Django:表单对象没有属性 cleaned_data - save() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17568705/