Longer username in Django 1.7

孤街醉人 提交于 2019-12-05 10:17:58

In Django 1.5 and above, the recommended approach would be to create a custom user model. Then you can make the username field exactly as you want.

I had the same problem few days ago. Finally, I ended just with cutting off first 30 characters of the (old) username (into the new database table), and adding a custom authentication backend that will check the email instead of user name. Terrible hack I know, and I'm planning to fix it as soon as I have some time. The idea is following:

I already have a model class that has one-to-one relation with djangos auth.User. I will add another field there called full_username.

class MyCustomUserModel(models.Model):
    user = models.OneToOneField(
            settings.AUTH_USER_MODEL, related_name="custom_user")
    full_username = models.CharField(max_length=80, ...)
    ...

Then, I'll add another custom authentication backend that will check this field as username. It would look something like this:

from django.contrib.auth.backends import ModelBackend

class FullUsernameAuthBackend(ModelBackend):
    def authenticate(self, username=None, password=None, **kwargs):
        UserModel = get_user_model()
        if username is None:
            username = kwargs.get(UserModel.USERNAME_FIELD)

        try:
            user = UserModel._default_manager.filter(custom_user__full_username=username)
            # If this doesn't work, will use (the second case):
            # user = MyCustomUserModel.objects.filter(full_username=username).user
        if user.check_password(password):
            return user
    except UserModel.DoesNotExist:
        # Adding exception MyCustomUserModel.DoesNotExist in "(the second case)"
        # Run the default password hasher once to reduce the timing
        # difference between an existing and a non-existing user (#20760).
        UserModel().set_password(password)

After this, you need to change settings.py:

AUTHENTICATION_BACKENDS = (
    "....FullUsernameAuthBackend",
    # I will have the email auth backend here also.
)

I hope that it will work.

Custom User Models are a huge change to make and aren't always compatible with apps. I solved it by running this very pragmatic migration. Note this only solves it at the database level.

migrations.RunSQL("alter table auth_user alter column username type varchar(254);")

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