简体   繁体   English

Django:带有附加字段的CreateView?

[英]Django: CreateView with additional field?

I am trying to program a Django CreateView (CBV), which takes instead of the user id the user email and determines (or creates) the user based on the email. 我正在尝试编写一个Django CreateView(CBV),它取代用户id而不是用户电子邮件,并根据电子邮件确定(或创建)用户。

My model does not contain anything special: 我的模型不包含任何特殊内容:

class Project(models.Model):
    name = models.CharField(_('Title'), max_length=100,)
    user = models.ForeignKey(User, verbose_name=_('user'),)
    ...

My forms.py adds the additional email field to the form: 我的forms.py将额外的电子邮件字段添加到表单中:

class ProjectCreateForm(forms.ModelForm):
    email = forms.EmailField(required=True, )

    class Meta:
        model = Project
        fields = ('name', ...,)

In my views.py, I am trying to determine if the user exists or should be created. 在我的views.py中,我试图确定用户是否存在或是否应该创建。 In both cases, the user id should be saved as part of the Project instance. 在这两种情况下,用户标识都应保存为Project实例的一部分。

class ProjectCreateDetails(CreateView):
    form_class = ProjectCreateForm
    template_name = '...'
    success_url = reverse_lazy('login') 
    model = Project

    def form_valid(self, form):
        try:
            user = User.objects.get(email=form.email)
        except User.DoesNotExist:
            user = User.objects.create_user(form.email, form.email, ''.join([random.choice(string.digits + string.letters) for i in range(0, 10)]))
            user.save()
        form.instance.user = user
        return super(ProjectCreateDetails, self).form_valid(form)

However I am facing an error that the 'Solution' object has no attribute 'email' . 但是我遇到一个错误,即'Solution' object has no attribute 'email'

Do I need to switch to a FormView instead of a CreateView? 我是否需要切换到FormView而不是CreateView?

You get the error 'Solution' object has no attribute 'email' because form.email is invalid. 您收到错误'Solution' object has no attribute 'email'因为form.email无效。 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. 当表单(包括模型表单)有效时,成功验证的数据在form.cleaned_data字典中可用。

Note that you don't need to call user.save() . 请注意,您不需要调用user.save() The create_user call has already added the user to the database. create_user调用已将用户添加到数据库。 You don't have to generate a random password either -- if password is None , then create_user will set an unusable password. 您不必生成随机密码 - 如果passwordNone ,则create_user将设置不可用的密码。

Finally, make sure that you do not include the user field in the ProjectCreateForm . 最后,确保您没有在ProjectCreateForm包含user字段。 You probably do not, but your code says fields = ('name', ...,) so I can't tell for sure. 你可能没有,但是你的代码说的是fields = ('name', ...,)所以我无法确定。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM