How to add max_length to allauth username

后端 未结 5 952
孤街浪徒
孤街浪徒 2021-01-25 07:08

I\'m using Django allauth as my user account framework for my django site. The docs show there is an ACCOUNT_USERNAME_MIN_LENGTH however there is no ACCOUNT_USERNAME_MAX_L

相关标签:
5条回答
  • 2021-01-25 07:26

    You should use a max length validator like below. More documentation about validators 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")
    
    0 讨论(0)
  • 2021-01-25 07:29

    This can be quickly done by extending DefaultAccountAdapter class and overriding the clean_username method. You need to also reference the clean_username once again after our custom validation to complete other inbuilt validations.

    It can be done as follows.

    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.
    

    Finally, point to the subclass in your settings.py

    ACCOUNT_ADAPTER = 'YourProject.adapter.UsernameMaxAdapter'
    

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

    0 讨论(0)
  • 2021-01-25 07:36

    Try importing with the full name like in your forms : from allauth.accouts import forms as AllauthForms class AllauthSignupForm(AllauthForms.SignupForm): ....

    i didn't test this and sorry i posted this with my phone i will reformat the answer soon

    0 讨论(0)
  • 2021-01-25 07:37

    Not sure if this is the best way but it works.

    After extending the SignupForm, Completely changed the username field with a new one that has the max_length parameter.

    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'}))
    
    0 讨论(0)
  • 2021-01-25 07:47

    I would like to explain why there is no ACCOUNT_USERNAME_MAX_LENGTH. If you open source code you will see that max_length validator comes from username model field https://github.com/pennersr/django-allauth/blob/330bf899dd77046fd0510221f3c12e69eb2bc64d/allauth/account/forms.py#L277

    username_field.max_length = get_username_max_length()
    

    Where get_username_max_length is function that actually pulls max_length value from User model 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
    

    First approach: So you could change max_length value directly on your User's model username field if you have it swapped.

    I don't think overriding form fields or __init__ method will actually work the it suggested by other answers, because assign of max_length happens in subclass of ACCOUNT_SIGNUP_FORM_CLASS https://github.com/pennersr/django-allauth/blob/330bf899dd77046fd0510221f3c12e69eb2bc64d/allauth/account/forms.py#L259

    class BaseSignupForm(_base_signup_form_class()):
    

    where _base_signup_form_class is function that gets your ACCOUNT_SIGNUP_FORM_CLASS

    Second approach: is to subclass SignupView and override it's SignupForm read Override signup view django-allauth and How to customize user profile when using django-allauth

    In that SignupForm you could actually do what @MehdiB or @PeterSobhi suggested.

    ImproperlyConfigured issue occurs because of https://github.com/pennersr/django-allauth/issues/1792

    So you be sure that these forms are defined in different python modules as per https://github.com/pennersr/django-allauth/issues/1749#issuecomment-304628013

    # 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"),
    
    0 讨论(0)
提交回复
热议问题