How do I check whether this user is anonymous or actually a user on my system?

后端 未结 4 866
粉色の甜心
粉色の甜心 2020-12-24 00:24
def index(request):
    the_user = request.user

In Django, how do I know if it\'s a real user or not? I tried:

if the_user:

相关标签:
4条回答
  • 2020-12-24 00:31

    You can check if request.user.is_anonymous returns True.

    0 讨论(0)
  • 2020-12-24 00:36

    I had a similar issue except this was on a page that the login_redirect_url was sent to. I had to put in the template:

    {% if user.is_authenticated %}
        Welcome Back, {{ username }}
    {% endif %}
    
    0 讨论(0)
  • 2020-12-24 00:37

    I know I'm doing a bit of grave digging here, but a Google search brought me to this page.

    If your view def requires that the user is logged in, you can implement the @login_required decorator:

    from django.contrib.auth.decorators import login_required
    
    @login_required
    def my_view(request):
        …
    
    0 讨论(0)
  • 2020-12-24 00:55

    An Alternative to

    if user.is_anonymous():
        # user is anon user
    

    is by testing to see what the id of the user object is:

    if user.id == None:
        # user is anon user
    else:
        # user is a real user
    

    see https://docs.djangoproject.com/en/dev/ref/contrib/auth/#anonymous-users

    0 讨论(0)
提交回复
热议问题