编写一个 django Allauth 适配器来检查我的值是否唯一

Write a django Alluth adapter that checks if a value i unique

我正在尝试检查 pid 的值是否唯一,但我无法设法让 alluth 适配器找到 pid 字段。有小费吗?什么都没发生,但如果我将 pid 值更改为 email,代码将在电子邮件字段上运行。我无法让 pid 字段使用此功能。也许我以错误的方式引用它并且提交的文件不属于默认帐户 adaptet-

class PidMaxAdapter(DefaultAccountAdapter):

def clean_pid(self, pid, user):
    user.profile.pid = pid
    if len(pid) > 9:
        raise ValidationError('Please enter a username value\
                                  less than the current one')
     
    # For other default validations.
    return DefaultAccountAdapter.clean_pid(self, pid)

创建自定义注册表单并在其中进行验证。

这是一个示例,其中我有一个禁用 recaptcha 的设置

from django import forms
from django.conf import settings

from allauth.account.forms import SignupForm as BaseSignupForm
from captcha.fields import ReCaptchaField

from .widgets import RefreshingCaptchaV3


class SignupForm(BaseSignupForm):
    """ Our signup form to integrate captcha """

    captcha = ReCaptchaField(
        label='',
        widget=RefreshingCaptchaV3()
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        if settings.DISABLE_RECAPTCHA:
            del self.fields['captcha']

您可以通过以下设置让 allauth 使用您的自定义表单;

ACCOUNT_FORMS = {
    'change_password': 'apps.accounts.forms.ChangePasswordForm',
    'reset_password': 'apps.accounts.forms.ResetPasswordForm',
    'signup': 'apps.accounts.forms.SignupForm',
}

如果将 pid 传递给表单,则可以将其作为 __init__ 中表单实例的属性,并在保存期间将其分配给配置文件。或者将 pid 作为字段,将表单的初始数据中的值传递给它,并将其作为隐藏输入(forms.HiddenInput() 是小部件)。

然后在 clean_pid() 中,您可以验证该值相对于 table 中的其他行是唯一的。根据您对这些数据的处理方式,使用 UUID 之类的东西最有意义,这样您就不必太担心值冲突。