Home:ALL Converter>How to get extended User custom fields in django template?

How to get extended User custom fields in django template?

Ask Time:2016-12-21T01:00:53         Author:Hariprasad

Json Formatter

I have extended django builtin user model. I am currently using django 1.10.

I am trying to display user name, short_name in template. note: short_name is extended field

<span> {{ request.user.profile.username  }} </span>
<span> {{ user.profile.username  }} </span>
{{ user.get_username }}
{{ user.username }}

this template tag is not working for django 1.10

I have used this link for creating custom user model https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html

using this I would like to display role based content.

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)

    employee_name = models.CharField(max_length=50)
    short_name = models.CharField(max_length=50)
    access = (
        ('admin', 'admin'),

        ('director', 'director'),
        ('management', 'management'),
        ('employee', 'employee'),
    )
    access_control = models.CharField(max_length=50, choices=access)
    YES_NO = (
        ('yes', 'Yes'),
        ('no', 'No'),
    )
    active = models.CharField(max_length=50, choices=YES_NO)

Added below lines in settings:

AUTH_PROFILE_MODULE = "user_login.UserProfile"

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.core.context_processors.request',
"django.contrib.auth.context_processors.auth",
)

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates'), ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

Author:Hariprasad,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/41247569/how-to-get-extended-user-custom-fields-in-django-template
German Alzate :

If you have a ForeignKey as relation with user, you CAN'T access it via user.userprofile.short_name, if you don't have defined related_name in your field, you would get it by user.userprofile_set.first().short_name, now, you can change the relation type to OneToOneField and use as user.userprofile.short_name, in this way only works with onetoone relation",
2016-12-20T17:29:21
Daniel Roseman :

Firstly, the relation from User to UserProfile is called userprofile.\n\nSecondly, username is on the main User model; your extra field is called short_name. So:\n\n{{ user.userprofile.short_name }}\n",
2016-12-20T17:06:18
yy