且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Django:具有其他字段的CreateView?

更新时间:2023-12-04 09:13:04

您收到错误'Solution'对象没有属性'email',因为 form.email 无效。验证数据永远不能用作表单或模型表单的属性。当表单(包括模型表单)有效时, form.cleaned_data 字典。

You get the error 'Solution' object has no attribute 'email' because form.email is invalid. Validated data is never available as attributes of a form or model form. When forms (including model forms) are valid, the successfully validated data is available in the form.cleaned_data dictionary.

请注意,不需要调用 user.save() create_user 调用已将用户添加到数据库中。您也不必生成随机密码-如果密码 None ,则 create_user 将设置无法使用的密码。

Note that you don't need to call user.save(). The create_user call has already added the user to the database. You don't have to generate a random password either -- if password is None, then create_user will set an unusable password.

最后,请确保您不包括 user $ c $ ProjectCreateForm 中的c>字段。您可能没有,但是您的代码显示 fields =('name',...,),所以我不确定。

Finally, make sure that you do not include the user field in the ProjectCreateForm. You probably do not, but your code says fields = ('name', ...,) so I can't tell for sure.

将其放在一起,您将获得以下(未经测试的)代码:

Put it together and you get the following (untested) code:

def form_valid(self, form):
    try:
        user = User.objects.get(email=form.cleaned_data['email'])
    except User.DoesNotExist:
        user = User.objects.create_user(form.cleaned_data['email'], form.cleaned_data['email']) 
    form.instance.user = user
    return super(ProjectCreateDetails, self).form_valid(form)