如何在 django-allauth 用户模型中添加更多字段?

时间:2021-08-01 18:29:04

标签: python django django-forms django-allauth

我想在 Django allauth 用户模型中添加更多字段。我以与 auth-user 的一对一关系创建了一个 User-Profile 模型,并尝试在 form.py 中创建 user-profile 对象。但是这个方法行不通。

根据此文档(https://docs.djangoproject.com/en/3.2/topics/auth/customizing/#extending-the-existing-user-model),我尝试扩展用户模型。但是注册后我在“UserProfile”中没有得到任何数据。

这是我的代码:

models.py

class UserProfile(models.Model):
    user = models.OneToOneField(User, related_name='userprofile', on_delete=models.CASCADE)
    profile_picture = models.ImageField()

forms.py

class CustomSignupForm(SignupForm):
    profile_picture = forms.ImageField()
 
    def signup(self, request, user):
        up = user.userprofile
        user.userprofile.profile_picture = self.cleaned_data['profile_picture']
        up.profile_picture = self.cleaned_data['profile_picture']
        user.save()
        up.save()
        return user

3 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

class CustomSignupForm(SignupForm):
    profile_picture = forms.ImageField()

这仅当您在数据库中有该表时才有效,假设您希望在表单中包含电子邮件,您不需要在模型中添加电子邮件,因为它已经在数据库中,因此您可以在表单中调用它。由

email = forms.EmailField()

或名字和姓氏,对于您的代码,您必须将其添加到模型中,因为数据库中没有相应的表

答案 2 :(得分:0)

看看我的代码也许对你有帮助 注意:我没有使用 allauth

models.py

def upload_to(instance, filename):
    profile_image_name = 'profile_images/userID_{0}/profile.jpg'.format(instance.user.id)
    full_path = os.path.join(settings.MEDIA_ROOT, profile_image_name)
    if os.path.exists(full_path):
        os.remove(full_path)
    return profile_image_name

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=CASCADE)
    profileimage = FileField(default="default.jpg", upload_to=upload_to, blank=True)
    user_bio = models.TextField(max_length=300, blank=True,null=True)

forms.py

class ProfileImageUpdate(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ['profileimage', 'user_bio']