在Django 1.5+中扩展用户名字段长度的“正确”方法是什么? [英] What is the 'right' way to extend the username field length in Django 1.5+?
问题描述
Django中的用户名限制为 max_length = 30
,并且自Django 1.5+起,也可以使用 USERNAME_FIELD $ c $进行设置c>。
Usernames in Django are limited to max_length=30
, and since Django 1.5+ they can also be set by using USERNAME_FIELD
.
但是,尚不清楚如何保持现有的 username
字段(包括所有功能),而仅更改 max_length
。我假设需要某种猴子修补程序,但是正确的方法并不是立即完成的。
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.
此问题不是以下内容的重复现有的问题指的是1.5之前的版本,而是询问一个非常具体的猴子补丁,而SO上的其他任何问题当前都未解决。
推荐答案
当前,我采用了以下似乎可行的猴子补丁:
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
这篇关于在Django 1.5+中扩展用户名字段长度的“正确”方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!