python - 如何在 Django 中查看用户的 DetailView?

标签 python django django-templates django-urls

我目前有一个用于 Django 的内置 UserDetailView

url(
    r'^users/(?P<pk>\d+)/$',
    DetailView.as_view(
        model = User,
        template_name = 'doors/users/detail.html'
    ),
    name = 'users_detail'
)

但是当我在模板中访问 user 时,它会显示当前登录 用户,而不是我使用 pk 的用户从 DetailUser 传递。我是否需要告诉 DetailUseruser 变量重命名为其他名称?如果是这样,我该怎么做?

最佳答案

django.contrib.auth.context_processors.auth 将 {{ user }} 模板上下文变量设置为 request.user 或 AnonymousUser。因此,它会覆盖由您的 DetailView 创建的 {{ user }} 上下文变量:

def auth(request):
    """
    Returns context variables required by apps that use Django's authentication
    system.

    If there is no 'user' attribute in the request, uses AnonymousUser (from
    django.contrib.auth).
    """
    # If we access request.user, request.session is accessed, which results in
    # 'Vary: Cookie' being sent in every request that uses this context
    # processor, which can easily be every request on a site if
    # TEMPLATE_CONTEXT_PROCESSORS has this context processor added.  This kills
    # the ability to cache.  So, we carefully ensure these attributes are lazy.
    # We don't use django.utils.functional.lazy() for User, because that
    # requires knowing the class of the object we want to proxy, which could
    # break with custom auth backends.  LazyObject is a less complete but more
    # flexible solution that is a good enough wrapper for 'User'.
    def get_user():
        if hasattr(request, 'user'):
            return request.user
        else:
            from django.contrib.auth.models import AnonymousUser
            return AnonymousUser()

    return {
        'user': SimpleLazyObject(get_user),
        'messages': messages.get_messages(request),
        'perms':  lazy(lambda: PermWrapper(get_user()), PermWrapper)(),
    }  

您可以通过 setting context_object_name 解决此问题.例如,这将启用 {{ user_object }} 上下文变量,设置为 DetailView 的用户:

url(
    r'^users/(?P<pk>\d+)/$',
    DetailView.as_view(
        model = User,
        template_name = 'doors/users/detail.html',
        context_object_name = 'user_object'
    ),
    name = 'users_detail'
)

深入挖掘,阅读 get_context_object_name() 的文档.

关于python - 如何在 Django 中查看用户的 DetailView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9867391/

相关文章:

python - 字符串模式匹配python

Python 字典的底层哈希数据结构

python - 如何从磁盘加载、处理数据,然后将数据与 python、pyqt、h5py 同时存储在一个通用的 hdf5 中?

python - Django REST 框架 - SearchFilter 不过滤

python - Django 不加载静态文件 (Pycharm)

python - Django 中的用户类型使用相同的登录名和注册表单

python - 使用 Python 将单行 .dat 文件合并为一个 .csv 文件

python - 为什么我的 uWSGI 找不到我的 Django 应用程序?

javascript函数没有被调用

Django:如果用户不是 super 用户,则在模板中隐藏按钮