Django 身份验证在一个页面上有效,但在另一个页面上无效

Django authentication works on a page, but not another

我一直在研究 Django 身份验证,但我偶然发现了一个问题:登录在页面(博客的 "post detail" 页面)上有效,但在主页上无效。

这是处理此 header

base.html 的一部分
{% if user.is_authenticated %}
    <a href="{% url 'blog.views.post_new' %}" class="top-menu header-icon"><span class="glyphicon glyphicon-plus"></span></a>
    <a href="{% url 'blog.views.post_draft_list' %}" class="top-menu header-icon"><span class="glyphicon glyphicon-edit"></span></a>
    <p class="top-menu">Hello, <a href="/edit/">{{ user.first_name }}</a>!<small> (<a href="{% url 'django.contrib.auth.views.logout' %}">Log out</a>)</small></p>
{% else %}
<form>
    {% csrf_token %}
    {% if next %}
    <input type="hidden" name="next" value="{{ next }}" />
    {% endif %}

    {{ login_form.as_p }}
</form>
{% endif %}

视图我觉得不错,反正就在这里

def login(request):
    if request.method == 'POST':
        login_form = CustomLoginForm(request.POST)

        email = request.POST.get('email')
        password = request.POST.get('password1')

        user = authenticate(email=email, password=password)

        if user is not None:
            if user.is_active:
                auth_login(request, user)
                return HttpResponseRedirect('/')
            else:
                return HttpResponse("Your Blog account is disabled.")
        else:
            print "Invalid login details: {0}, {1}".format(email, password)
            return HttpResponse("Invalid login details supplied. Get back to the <a href=\"/\">homepage</a>.")
    else:
        login_form = CustomLoginForm()

    return render(request, 'blog/post_list.html', {})

def post_list(request):
    posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')
    user = CustomUser.objects.all()

    user_form = CustomUserCreationForm()
    login_form = CustomLoginForm()

    return render(request, 'blog/post_list.html', {'posts': posts, 'user_form': user_form, 'login_form': login_form, 'user': user})

我认为问题的核心可能出在 base.html 文件的 header 或视图上。

这是我在主页上看到的(即使我已登录)

这是我在 post-detail 页面上看到的(这也是我应该在主页上看到的)

有什么想法吗?

你的问题在这里:

user = CustomUser.objects.all()

然后

return render(request, 'blog/post_list.html', 
              {'posts': posts, 'user_form': user_form, 
               'login_form': login_form, 'user': user})

您正在将由 CustomUser 个对象组成的查询集结果作为请求上下文中的 user 传递。它覆盖由 django.contrib.auth.context_processors.auth 上下文处理器分配的 user 变量。

要解决问题,只需将模板变量的名称更改为其他名称,例如:

return render(...
              'users': user})