Overwrite maxlength/minlength of username by Django User model in the ModelForm

1.7k Views Asked by At

Try to overwrite User models by the following code, but somehow I cannot overwrite the max_length and min_length of username.

More specifically, when I check by python manage.py shell, I do overwrite them. But it seems has no effect on the html which was rendered(username maxlength is still 150).

Don't know which parts get wrong, please help.

from django import forms
from django.contrib.auth.models import User

class RegistrationForm(forms.ModelForm):

def __init__(self, *args, **kwargs):
    super(RegistrationForm, self).__init__(*args, **kwargs)
    email = self.fields['email']
    username = self.fields['username']
    email.required = True
    email.label_suffix = ' '
    username.label_suffix = ' '
    ######### this is not work!!!###############
    username.min_length = 6
    username.max_length = 30
    ############################################

class Meta:
    model = User
    fields = ('username', 'email')
    labels = {
        'username': '帳號',
    }
    help_texts = {
        'username': '',
    }
2

There are 2 best solutions below

0
On

Instead of modifying the form, you should modify/override the model.

I recommend using django-auth-tools for building your own custom user model. It supplies basic models, views and forms which can be easily extended.

1
On

If you are trying to override just the model form field, you could do something like this

class RegistrationForm(forms.ModelForm):
    username = forms.CharField(required=True, min_length=6, max_length=30)

class Meta:
        model = User
        fields = ('username', 'email')

or

class RegistrationForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(RegistrationForm, self).__init__(*args, **kwargs)
        self.fields['username'] = forms.CharField(required=True, min_length=6, max_length=30)

class Meta:
        model = User
        fields = ('username', 'email')

But I would recommend creating a Custom User Model inherited from AbstractBaseUser to override the username or email field as documented in https://docs.djangoproject.com/en/1.10/topics/auth/customizing/