问题
Usernames in Django are limited to max_length=30
, and since Django 1.5+ they can also be set by using USERNAME_FIELD
.
However, it isn't clear how the existing username
field can be kept intact (with all the functionality it has) while only changing max_length
. I assume some sort of monkey patching is required, but it isn't immediate what the right way to do so is.
This question is not a duplicate of existing questions that refer to versions prior to 1.5, rather it asks about a very specific monkey patch that isn't currently addressed in any other question on SO.
回答1:
Currently, I have resorted to the following monkey patch which seems to work:
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import AbstractUser
class MyUser(AbstractUser):
pass
USERNAME_LENGTH = 50
MyUser._meta.get_field('username').max_length = USERNAME_LENGTH
MyUser._meta.get_field('username').validators[0].limit_value = USERNAME_LENGTH
MyUser._meta.get_field('username').validators[1].limit_value = USERNAME_LENGTH
UserCreationForm.base_fields['username'].max_length = USERNAME_LENGTH
UserCreationForm.base_fields['username'].validators[0].limit_value = USERNAME_LENGTH
来源:https://stackoverflow.com/questions/25136282/what-is-the-right-way-to-extend-the-username-field-length-in-django-1-5