【问题标题】:How to add more fields in django-allauth User model?如何在 django-allauth 用户模型中添加更多字段?
【发布时间】:2021-10-07 07:35:00
【问题描述】:

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

根据这个文档(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

【问题讨论】:

    标签: python django django-forms django-allauth


    【解决方案1】:

    【讨论】:

    【解决方案2】:
    class CustomSignupForm(SignupForm):
        profile_picture = forms.ImageField()
    

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

    email = forms.EmailField()
    

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

    【讨论】:

    【解决方案3】:

    看看我的代码也许对你有帮助 注意:我没有使用 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']
       
    

    【讨论】:

      猜你喜欢
      • 2020-01-20
      • 2019-12-30
      • 2019-06-26
      • 1970-01-01
      • 1970-01-01
      • 2017-01-10
      • 1970-01-01
      • 1970-01-01
      • 2018-05-08
      相关资源
      最近更新 更多