Can I change Django's auth_user.username field to be 100 chars long without breaking anything?

二次信任 提交于 2019-12-03 03:07:46

You need to monkey-patch max-length in several places: model-field's description, form-field's description and max-length validators. Max-length validators are attached to form-fields as well as model-fields.

Here is a code snippet, which will patch everything:

https://gist.github.com/1143957 (tested with django 1.2 and 1.3)

Update: Good news! Since django 1.5 you can override user model: Customizing the User model

There is no harm in doing that. Just change the length in the model and in the database :)

Create a user profile model, add your very-long-username field there, and use it. of course this renders the genuine username field useless, but it is much better than hacking Django code, which will get you into trouble when you need to upgrade it.

For me, the code below works and is simple well.

from django.contrib.auth.models import AbstractUser

class MyUser(AbstractUser):
    ....
    # your custom fields

MyUser._meta.get_field('username').max_length = 255  # or 100

after you can run your migration

If you change the database manually as well as the model accordingly then there should be no problem.

You can also change back otherwise, and I would say make a backup just in case but I'm not sure its even necessary

for future needs this is the best and easiest way i found out:

https://github.com/GoodCloud/django-longer-username

Another solution is to change your authentication code. When a new user signs up, they enter an email, you save this in the email field so you have it, and if their email is >30 characters, you shorten it before putting it into the user field. Then, change your login authentication for new logins.

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