2

I'm not advanced in Django and would like to know how and if it's possible to do it.

I need to override Django's user model, and change the fields "username" to "sr_usuario" and "password" to "sr_password", but I would like to continue using all Django's default authentication scheme and permissions. I want not only to change the description in the database or a label, I want to change the name of the field in the model, for when for example I needed to make a query, I would use User.objects.filter(sr_usuario="user_name") and everything would work usually.

It's possible? I couldn't find anything in the documentation or on forums I've searched.

Thank you very much in advance!

3 Answers3

3

Yes, if you want to override the User Model you need to add to your settings:

AUTH_USER_MODEL = "<THE PATH OF THE USER MODEL>"

And in that model extend it using the AbstractUser

Django Documentation here: https://docs.djangoproject.com/en/4.1/topics/auth/customizing/#using-a-custom-user-model-when-starting-a-project

cerwind
  • 122
  • 2
  • 5
  • 2
    this is correct, however, with the caveat that it doesnt necessarily support an existing user model which is already created. – Swift Oct 24 '22 at 21:49
0

This is not possible, as all the django code is strictly coupled to the fields in the user.

You can, however, create a custom authentication backend and use a custom user model with the field names mentioned. But this would require a lot of coding.

JanMalte
  • 934
  • 6
  • 17
  • 1
    As per cerwind's answer, you can subclass from AbstractUser, but it is only recommended when doing so from the initial development of the project, i.e. its not recommended to try and abstract the user model after the first migration has been run and the project has been developed past being able to throw away the database. – Swift Oct 24 '22 at 21:51
0
    You should subclass AbstractBaseUser [doc], and set this custom user model as AUTH_USER_MODEL [doc] in your settings.
    This will instruct Django to use your custom user model everywhere, and retain all the built-in auth/permission behavior.
    For example:
    from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
    from django.db import models
    
    class MyUser(AbstractBaseUser, PermissionsMixin):
        sr_usuario = models.CharField(max_length=100, unique=True)
        sr_password = models.CharField(max_length=100)
        # ...
    Then use this in settings:
    AUTH_USER_MODEL = 'my_app.MyUser'
    Note that migrations can be tricky here, so it is best to do this at the start of a new project.

class MyUser(AbstractUser):
    username = None
    sr_usuario = models.CharField(max_length=150, unique=True)

    USERNAME_FIELD = 'sr_usuario'
  • Perfect answer but it would be great if you separated them. You will help not only the person who made the question but thousands more in the furture. – Elias Prado Oct 27 '22 at 00:12