覆盖 Google-Auth 用户创建

Overriding Google-Auth user creation

我添加了 google 登录名,当我在继续后选择一个帐户时,我得到以下信息。

回溯(最近调用最后):

  File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\allauth\utils.py", line 229, in deserialize_instance
    v = f.from_db_value(v, None, None)

During handling of the above exception ('ImageField' object has no attribute 'from_db_value'), another exception occurred:
  File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\django\views\generic\base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\allauth\socialaccount\views.py", line 39, in dispatch
    self.sociallogin = SocialLogin.deserialize(data)
  File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\allauth\socialaccount\models.py", line 215, in deserialize
    user = deserialize_instance(get_user_model(), data["user"])
  File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\allauth\socialaccount\adapter.py", line 189, in deserialize_instance
    return deserialize_instance(model, data)
  File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\allauth\utils.py", line 231, in deserialize_instance
    raise ImproperlyConfigured(

Exception Type: ImproperlyConfigured at /accounts/social/signup/
Exception Value: Unable to auto serialize field 'verified', custom serialization override required

我有一个已验证字段的抽象用户,我想创建一个具有 google all-auth 的默认用户。我将如何处理?它说我需要序列化验证和头像仅有的两个图像字段。

from django.db import models
from django.contrib.auth.models import AbstractUser
from phonenumber_field.modelfields import PhoneNumberField
from django.templatetags.static import static

class Profile(AbstractUser):
    bio = models.TextField(max_length=100, blank=True)
    phone_number = PhoneNumberField(max_length=25, region='US')
    birth_date = models.DateField(blank = True, null = True) 
    is_doctor = models.BooleanField(default=False)
    verified = models.ImageField(default='',upload_to='media/doctor')
    date_created = models.DateTimeField(auto_now_add=True)
    avatar = models.ImageField(upload_to='media/avatars',null=True)

    gender_choices = (('others', 'Others'),('male', 'Male'),('female' ,'Female'))
    gender = models.CharField(max_length=10, choices=gender_choices,default='others')
    default_pic_mapping = { 'others': 'default.png', 'male': 'default.png', 'female': 'default.png'}

    def get_profile_pic_url(self):
        if not self.avatar:
            return static('img/{}'.format(self.default_pic_mapping[self.gender]))
        return self.avatar.url
        

在 models.py

中创建自定义用户模型

您可以使用 Django 示例,或按照我们下面的示例进行操作。我们将在这里简化流程。

accounts/models.py

from django.db import models
from django.contrib.auth.models import (
    BaseUserManager, AbstractBaseUser
)


class User(AbstractBaseUser):
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )
    is_active = models.BooleanField(default=True)
    staff = models.BooleanField(default=False) # a admin user; non super-user
    admin = models.BooleanField(default=False) # a superuser

    # notice the absence of a "Password field", that is built in.

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = [] # Email & Password are required by default.

    def get_full_name(self):
        # The user is identified by their email address
        return self.email

    def get_short_name(self):
        # The user is identified by their email address
        return self.email

    def __str__(self):
        return self.email

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        return self.staff

    @property
    def is_admin(self):
        "Is the user a admin member?"
        return self.admin

更新设置模块(又名settings.py):

1。 运行 迁移

python manage.py makemigrations
python manage.py migrate
  1. 更新settings.py
    AUTH_USER_MODEL = 'accounts.User'
  1. 运行 再次迁移
    python manage.py makemigrations
    python manage.py migrate
  1. 创建超级用户
    python manage.py createsuperuser
  1. 一些实用的想法

设置AUTH_USER_MODEL意味着我们可以使用许多利用Django用户模型的第三方包;想到 Django Rest Framework、Django AllAuth、Python Social Auth 等软件包。

现在,每次需要用户模型时,使用:

    from django.contrib.auth import get_user_model
    User = get_user_model()

这为其他开发人员和我们未来的自己提供了只有 well-thought-out 代码才能提供的那种安心; get_user_model 是核心 Django 开发人员很久以前决定的那些部分之一。

6 但是用户外键呢?在某些时候你会遇到这种情况:

    class SomeModel(models.Model):
        user = models.ForeignKey(...)

那有什么用呢? get_user_model accounts.models.User 还是什么?实际上,无论用户模型自定义如何,您每次都会使用 settings.AUTH_USER_MODEL。所以它看起来像这样:

    from django.conf import settings
    
    User = settings.AUTH_USER_MODEL
    
    class SomeModel(models.Model):
        user = models.ForeignKey(User, on_delete=models.CASCADE)

希望这能回答您的问题...?