简体   繁体   English

在 Django 中使用 context_processors.py 时,如何避免在登录页面上请求用户?

[英]How to avoid requesting user on login page while using context_processors.py in Django?

I wanted to pass variables with the User information, that is linked to a Clients model through a OneToOneField to the django.contrib.auth.models , onto the base.html file.我想将带有 User 信息的变量传递给base.html文件,该变量通过 OneToOneField 链接到Clients模型到django.contrib.auth.models

So, I created a context_processors.py with the following code所以,我用下面的代码创建了一个context_processors.py

from django.contrib.auth.models import User

    def userData(request):  
        user = request.user
        u = User.objects.get(username=user)
        us = u.clients.first_name
        uv = u.clients.avatar
        return {
            'u': u,
            'us': us,
            'uv': uv
        }

Everything was working fine, until I logged out.一切正常,直到我退出。

When I try to login again, I get the accounts/login url and get a当我再次尝试登录时,我得到了accounts/login URL 并得到了一个

DoesNotExist at /accounts/login/
User matching query does not exist.

Well your request.user is already a User , so it makes not much sense to fetch it again.嗯,你的request.user已经一个User ,所以它是没有多大意义,再次读取它。

You can simply check if the user is logged in:您可以简单地检查用户是否已登录:

def userData(request):
    if request.user.is_authenticated:
        return {
            'u': request.user,
            'us': request.user.clients.first_name,
            'uv': request.user.clients.avatar,
        }
    return {}

Note : the name clients is plular , so that suggests a collection of Client s.注意:名称clients复数,因此建议Client集合 Normally model names are singular (so Client instead of Clients ), and the related name of a OneToOneField should, if you specify it yourself, be singular as well.通常模型名称是单数(因此Client而不是Clients ),并且OneToOneField的相关名称(如果您自己指定)也应该是单数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM