What is the 'right' way to extend the username field length in Django 1.5+?

一笑奈何 提交于 2019-12-14 02:52:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!