django - 如何在 django 模板中获取扩展的用户自定义字段?

标签 django

我扩展了 django 内置用户模型。我目前使用的是 django 1.10。

我正在尝试在模板中显示用户名,short_name。 注意:short_name是扩展字段

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

此模板标签不适用于 django 1.10

我已使用此链接创建自定义用户模型 https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html

使用它我想显示基于角色的内容。

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',
            ],
        },
    },
]

最佳答案

如果您有一个与 user 相关的 ForeignKey,则您无法通过 user.userprofile.short_name 访问它,如果您不这样做您的字段中没有定义lated_name,您可以通过user.userprofile_set.first().short_name获取它,现在,您可以将关系类型更改为 OneToOneField 并用作 user.userprofile.short_name,这种方式仅适用于 onetoone 关系

关于django - 如何在 django 模板中获取扩展的用户自定义字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41247569/

相关文章:

python - pip install MySQL-python 出错

python - 一种在简单界面后转换和组合多种数据类型的模式

javascript - SB Admin 2 侧边栏不折叠

python - django 模型对象属性在哪里以及如何定义?

jquery - 405 (METHOD NOT ALLOWED) for ajax request with django

django - “NoneType”对象没有属性 'save' Django

python - wsgi.py 丢失,manage.py 存在

python - 在 Django REST 中增加计数器字段的最佳位置

python - django-admin 中的多模型版本

python - 如何在 Django 中添加我自己的 html 模板