Django All-Auth - 在创建帐户时针对链接对象进行验证



好的,所以,使用 Django 和 All-Auth 处理注册(没有社交注册),我想做的是当我在用户名中时,我想将其与第二个表的行进行比较。

长话短说,user充当(现实世界)玩家的标识符,玩家可以有很多character,我想检查以确保没有使用与用户名匹配的character名称,并注册用户并为他们创建与其用户名匹配的角色,如果可以的话。

需要明确的是:

如果具有用户尝试注册的名称的字符不存在,则让用户也注册并创建该字符。

如果存在具有用户尝试注册的名称的字符,则返回一个错误,大意为"名称已被占用"。

这不仅仅是用户配置文件的一对一扩展,因为每个用户可能有很多字符 - 而不仅仅是一个。不需要额外的表单字段,因为必要的数据应该已经作为用户名的一部分输入。

我似乎不理解验证,因为它以一种使这成为可能的方式以全身份验证的方式发生,并且我已经阅读了源代码和 readthedocs 页面的一部分。

我很乐意扩展或回答有关此事的问题。(我相信我的服务器上的python版本是2.x。


我认为已经回答了一个额外的问题:

我还想出于任何原因保留一些角色名称作为受保护的角色,这样人们就无法注册帐户来匹配(基本上是目标社区中的冒名顶替者)。我可以通过什么方式指示名称不能使用,因为它是受保护的名称,并在注册时提供额外的数据?

我没有做任何你想做的事情,所以我不能给你确切的代码,但我相信解决方案是让你定义自己的 DefaultAccountAdapter,并尝试覆盖new_usersave_user方法。

要编写自己的适配器,您需要设置以下设置

ACCOUNT_ADAPTER = 'path.to.adapters.YourAccountAdapter'

然后定义

from allauth.account.adapter import DefaultAccountAdapter
class YourAccountAdapter(DefaultAccountAdapter):
    def clean_username(self, username, shallow=False):
        # -----------------------
        # do our validation first
        # -----------------------
        # character exists with username?
        if (YourModel.objects.filter(loginname__iexact=str(username))):
            # let's poke this a bit
            char = YourModel.objects.get(loginname__iexact=str(username))
            # is it a protected character name?
            if char.protected:
                raise ValidationError("Name belongs to protected character, please contact site admin to claim")
            else:
                raise ValidationError("Character with name exists, cannot use as a login name")
        # -----------------------------------------
        # if that went okay, call and return parent
        # -----------------------------------------
        return super(YourAccountAdapter, self).clean_username(username, shallow)

见 http://django-allauth.readthedocs.org/en/latest/advanced.html

另一种选择(或也可以做的事情)是使用您自己的注册表单,您可以在接受表单之前预先验证用户名字段。为此,您需要在设置中添加以下内容

ACCOUNT_FORMS = { 'signup': 'path.to.forms.AllauthSignupForm'}

,然后使用

from allauth.account.forms import SignupForm
from django.core.validators import ValidationError
class AllauthSignupForm(SignupForm):
    def clean_username(self):
        # check for duplicates here and then
        if duplicate:
             raise ValidationError("Username is not allowed")
    return org

最新更新