如何将max_length添加到allauth用户名

时间:2018-05-27 03:06:23

标签: python django django-allauth

我使用Django allauth作为我的django网站的用户帐户框架。文档显示有ACCOUNT_USERNAME_MIN_LENGTH,但由于某种原因没有ACCOUNT_USERNAME_MAX_LENGTH

有没有办法为用户名创建最大长度?

这是我的自定义allauth注册表单 - 也许我可以在这里做点什么?:

class AllauthSignupForm(forms.Form):

    captcha = ReCaptchaField(
        public_key=config("RECAPTCHA_PUBLIC_KEY"),
        private_key=config("RECAPTCHA_PRIVATE_KEY"),
    )

    class Meta:
        model = User

    def signup(self, request, user):
        """ Required, or else it throws deprecation warnings """
        pass

编辑:尝试继承SignupView

draft1 / forms.py

class AllauthSignupForm(SignupForm):
    def __init__(self, *args, **kwargs):
        super(AllauthSignupForm, self).__init__(*args, **kwargs)
        self.fields['username']['validators'] += MaxLengthValidator(150,
                                                                    "Username should be less than 150 character long")

    captcha = ReCaptchaField(
        public_key=config("RECAPTCHA_PUBLIC_KEY"),
        private_key=config("RECAPTCHA_PRIVATE_KEY"),
    )

    class Meta:
        model = User

    def signup(self, request, user):
        """ Required, or else it throws deprecation warnings """
        pass

draft1 / views.py

from allauth.account.views import SignupView

class MySignupView(SignupView):
    form_class = AllauthSignupForm

allauth /帐户/ urls.py

url(r"^signup/$", MySignupView.as_view(), name="account_signup"),

draft1 / settings.py

ACCOUNT_SIGNUP_FORM_CLASS = 'draft1.forms.AllauthSignupForm'

以上代码返回此错误:

Traceback (most recent call last):
  File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/utils/autoreload.py", line 228, in wrapper
    fn(*args, **kwargs)
  File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run
    self.check(display_num_errors=True)
  File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/core/management/base.py", line 359, in check
    include_deployment_checks=include_deployment_checks,
  File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/core/management/base.py", line 346, in _run_checks
    return checks.run_checks(**kwargs)
  File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/core/checks/registry.py", line 81, in run_checks
    new_errors = check(app_configs=app_configs)
  File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/core/checks/urls.py", line 16, in check_url_config
    return check_resolver(resolver)
  File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/core/checks/urls.py", line 26, in check_resolver
    return check_method()
  File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/urls/resolvers.py", line 254, in check
    for pattern in self.url_patterns:
  File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/urls/resolvers.py", line 405, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/urls/resolvers.py", line 398, in urlconf_module
    return import_module(self.urlconf_name)
  File "/Users/zorgan/Desktop/postr1/lib/python3.5/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 986, in _gcd_import
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 665, in exec_module
  File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
  File "/Users/zorgan/Desktop/vorsso/venvor/draft1/urls.py", line 6, in <module>
    from . import views
  File "/Users/zorgan/Desktop/vorsso/venvor/draft1/views.py", line 11, in <module>
    from .forms import UserSettingsForm
  File "/Users/zorgan/Desktop/vorsso/venvor/draft1/forms.py", line 8, in <module>
    from allauth.account.forms import SignupForm
  File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/allauth/account/forms.py", line 228, in <module>
    class BaseSignupForm(_base_signup_form_class()):
  File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/allauth/account/forms.py", line 216, in _base_signup_form_class
    fc_classname))
django.core.exceptions.ImproperlyConfigured: Module "draft1.forms" does not define a "AllauthSignupForm" class

5 个答案:

答案 0 :(得分:1)

这可以通过扩展DefaultAccountAdapter类并覆盖clean_username方法来快速完成。自定义验证后,您还需要再次引用clean_username,以完成其他内置验证。

可以完成以下操作。

from allauth.account.adapter import DefaultAccountAdapter
from django.forms import ValidationError

class UsernameMaxAdapter(DefaultAccountAdapter):

    def clean_username(self, username):
        if len(username) > 'Your Max Size':
            raise ValidationError('Please enter a username value less than the current one')
        return DefaultAccountAdapter.clean_username(self,username) # For other default validations.

最后,指向您的settings.py

中的子类
ACCOUNT_ADAPTER = 'YourProject.adapter.UsernameMaxAdapter'

参考:https://github.com/pennersr/django-allauth/blob/8fbbf8c1d32832d72de5ed1c7fd77600af57ea6f/allauth/account/adapter.py#L244

答案 1 :(得分:0)

您应该使用如下所示的最大长度验证器。有关验证程序here的更多文档。

from django.core.validators import MaxLengthValidator
from allauth.account.forms import SignupForm
class AllauthSignupForm(SignupForm):
    def __init__(self, *args, **kwargs):
        self.fields['username']['validators'] += MaxLengthValidator(150, "Username should be less than 150 character long")

答案 2 :(得分:0)

不确定这是否是最好的方法,但它有效。

在扩展username后,使用具有max_length参数的新字段完全更改了from django import forms from django.utils.translation import ugettext_lazy as _ from allauth.account.forms import SignupForm class AllauthSignupForm(SignupForm): username = forms.CharField(label=_("Username"), min_length=5, max_length=20, # Change this widget=forms.TextInput( attrs={'placeholder': _('Username'), 'autofocus': 'autofocus'})) 字段。

    # Area of Polygon using Shoelace formula
# http://en.wikipedia.org/wiki/Shoelace_formula
# FB - 20120218
# corners must be ordered in clockwise or counter-clockwise direction
def PolygonArea(corners):
    n = len(corners) # of corners
    area = 0.0
    for i in range(n):
        j = (i + 1) % n
        area += corners[i][0] * corners[j][1]
        area -= corners[j][0] * corners[i][1]
    area = abs(area) / 2.0
    return area

# examples
corners = [(2.0, 1.0), (4.0, 5.0), (7.0, 8.0)]
print PolygonArea(corners)
corners = [(3.0, 4.0), (5.0, 11.0), (12.0, 8.0), (9.0, 5.0), (5.0, 6.0)]
print PolygonArea(corners)


let N           = number of points
let points[N+1] = the array of points
swap points[1] with the point with the lowest y-coordinate
sort points by polar angle with points[1]

# We want points[0] to be a sentinel point that will stop the loop.
let points[0] = points[N]

# M will denote the number of points on the convex hull.
let M = 1
for i = 2 to N:
    # Find next valid point on convex hull.
    while ccw(points[M-1], points[M], points[i]) <= 0:
        if M > 1:
            M -= 1
            continue
        # All points are collinear
        else if i == N:
            break
        else
            i += 1

    # Update M and swap points[i] to the correct place.
    # This code is wrong as explained in the talk page. When M and i are the same, the algorithm ends up in an infinite loop.
    M += 1
    swap points[M] with points[i]

答案 3 :(得分:0)

我想解释为什么没有ACCOUNT_USERNAME_MAX_LENGTH。如果您打开源代码,您会看到max_length验证程序来自username模型字段https://github.com/pennersr/django-allauth/blob/330bf899dd77046fd0510221f3c12e69eb2bc64d/allauth/account/forms.py#L277

username_field.max_length = get_username_max_length()

其中get_username_max_length是实际从max_length模型中获取User值的函数https://github.com/pennersr/django-allauth/blob/8fbbf8c1d32832d72de5ed1c7fd77600af57ea6f/allauth/utils.py#L64

def get_username_max_length():
    from .account.app_settings import USER_MODEL_USERNAME_FIELD
    if USER_MODEL_USERNAME_FIELD is not None:
        User = get_user_model()
        max_length = User._meta.get_field(USER_MODEL_USERNAME_FIELD).max_length
    else:
        max_length = 0
    return max_length

第一种方法:因此,如果您已将max_length的{​​{1}}模型User字段更改为username,则可以直接更改__init__值。

我认为覆盖表单字段或max_length方法实际上不会像其他答案所建议的那样工作,因为ACCOUNT_SIGNUP_FORM_CLASS的分配发生在class BaseSignupForm(_base_signup_form_class()): https://github.com/pennersr/django-allauth/blob/330bf899dd77046fd0510221f3c12e69eb2bc64d/allauth/account/forms.py#L259的子类中

_base_signup_form_class

其中ACCOUNT_SIGNUP_FORM_CLASS是获取SignupView

的函数

第二种方法:是子类SignupForm并覆盖它SignupForm阅读Override signup view django-allauthHow to customize user profile when using django-allauth

在那个ImproperlyConfigured你实际上可以做@MehdiB或@PeterSobhi建议的事情。

由于https://github.com/pennersr/django-allauth/issues/1792

,会出现

# base/forms.py # this is form that your ACCOUNT_SIGNUP_FORM_CLASS is points to class BaseSignupForm(forms.Form): captcha = ReCaptchaField( public_key=config("RECAPTCHA_PUBLIC_KEY"), private_key=config("RECAPTCHA_PRIVATE_KEY"), ) class Meta: model = User def signup(self, request, user): """ Required, or else it throws deprecation warnings """ pass # data1/forms.py # this is your signup form from django.core.validators import MaxLengthValidator from allauth.account.forms import SignupForm class MySignupForm(SignupForm): def __init__(self, *args, **kwargs): super(MySignupForm, self).__init__(*args, **kwargs) self.fields['username']['validators'] += MaxLengthValidator(150, "Username should be less than 150 character long") # views.py from allauth.account.views import SignupView class MySignupView(SignupView): form_class = MySignupForm # urls.py url(r"^signup/$", MySignupView.as_view(), name="account_signup"), 问题

因此,请确保根据https://github.com/pennersr/django-allauth/issues/1749#issuecomment-304628013

在不同的python模块中定义这些表单
{{1}}

答案 4 :(得分:0)

尝试使用全名(如您的表格)进行导入:  从allauth.accouts导入表单作为AllauthForms 类AllauthSignupForm(AllauthForms.SignupForm):     ....

我没有对此进行测试,很抱歉我用手机发布了此信息,我将尽快重新设置答案格式