Search code examples
pythonsqldjangopostgresqldjango-login

How to Access the custom column from auth_user table in Django?


I am able to access the Pre define column

(id, password, last_login,is_superuser, username, first_name, 
       last_name, email, is_staff, is_active, date_joined )

of auth_user table .

after that I added the new column img_url in auth_user table.

but from same code request.user.img_url It is not accessing the value of img_url column .

How I can access img_url column ?

Thank You.


Solution

  • You have two choices here:

    1. You can either extend your existing user model
    2. Or You can implement a custome user model

    For first Option (Extending you existing model) You can do like:

    from django.contrib.auth.models import User
    
    class NewUserModel(models.Model):
        user = models.OneToOneField(User, on_delete=models.CASCADE)
        new_field_name = models.CharField(max_length=100)
    

    then use it like this:

    u = User.objects.get(username='fsmith')
    freds_department = u.employee.department
    

    For second option (Custom User Model) You can do like:

    Create a model in sample_app and give its reference in settings.py like:

    AUTH_USER_MODEL = 'sample_app.MyUser'
    

    For more information:

    Customizing authentication in Django