我正在尝试编写一个 Django CreateView (CBV),它使用用户电子邮件而不是用户 ID,并根据电子邮件确定(或创建)用户。
我的模型不包含任何特殊内容:
class Project(models.Model):
name = models.CharField(_('Title'), max_length=100,)
user = models.ForeignKey(User, verbose_name=_('user'),)
...
我的 forms.py 将额外的电子邮件字段添加到表单中:
class ProjectCreateForm(forms.ModelForm):
email = forms.EmailField(required=True, )
class Meta:
model = Project
fields = ('name', ...,)
在我的views.py 中,我试图确定用户是否存在或应该被创建。在这两种情况下,用户 ID 都应保存为 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)
但是我面临一个错误,即'Solution' object has no attribute 'email'
.
我是否需要切换到 FormView 而不是 CreateView?