处理自定义用户模型 Django-Allauth

Handle Custom User Model Django-Allauth

我有一个从 Django 的 User 扩展而来的 自定义用户模型 ,我想注册该用户模型而不仅仅是默认的。

为此,我根据 allauth doc 使用 ACCOUNT_SIGNUP_FORM_CLASS 设置。

这是我在 settings.py:

ACCOUNT_SIGNUP_FORM_CLASS = 'myapp.forms.SignupForm'

并且在myapp/forms.py中:

class SignupForm(UserCreationForm):

    class Meta(UserCreationForm.Meta):
        model = MyUser

    def signup(self, request, user):
        print('test')
        user.save()
        MyUser(user=user).save()

应该执行signup()函数:

This class [SignupForm] should implement a def signup(self, request, user) method, where user represents the newly signed up user.

但它不是(test 未打印)。只有 User 被保存, MyUser 没有。 我做错了什么?

您在这里混合了 2 种东西:

  1. 您使用 ACCOUNT_SIGNUP_FORM_CLASS 是为了告诉 all-auth 使用什么自定义注册表单
  2. 您的自定义注册表单继承自 Django 自己的 UserCreationForm

这样 signup() 方法将永远不会被调用。

如果您看一下 this line,您会发现那里是调用 signup() 方法的地方。 因此,如果您想充分利用 all-auth 的内置表单,我建议您从 all-auth 库中继承 SignupForm

再一次,根据您的方法判断,您可能想考虑设置 AUTH_USER_MODEL=MyUser