Django is_authenticated()在索引页上总是返回false,但在其他页上则不返回



我在网站的不同页面上使用相同的layout.html,其中包括登录检查。

{% if user.is_authenticated %}
Signed in as <strong>{{ user.username }}</strong>.
{% else %}
Not signed in.
{% endif %}

如果我登录,该语句在除索引页之外的所有页上都返回true。因此,我怀疑我注册的网址有问题。但是,我找不到问题。

我的网站/uls.py:

from django.contrib import admin
from django.urls import include, path
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include("app.urls")),
]

我的应用程序/urls.py:

from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name = "index"),
path("login", views.login_view, name = "login"),
path("logout", views.logout_view, name = "logout"),
path("register", views.register, name = "register"),
path("lobby/<str:lobby_name>/", views.lobby, name = "lobby")
]

我的网站/设置.py:

import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '123'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']

INSTALLED_APPS = [
'channels',
'app',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'site.urls'

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

WSGI_APPLICATION = 'site.wsgi.application'
ASGI_APPLICATION = 'site.asgi.application'
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": [('127.0.0.1' , 6379)],
},
},
}
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
AUTH_USER_MODEL = 'app.User'

AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]


LOGIN_REDIRECT_URL = '/lobby/'
LOGIN_URL = '/login/'

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]

我的应用程序/视图.py

from django.contrib.auth import authenticate, login, logout
from django.db import IntegrityError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.shortcuts import redirect
from django.http import Http404
from django.http import HttpResponseForbidden
from django import forms
from io import BytesIO
from PIL import Image
from django.contrib.auth.decorators import login_required
from .models import *

def index(request):
return render(request, "app/index.html",{
"user": User.username
})

def login_view(request):
if request.method == "POST":

user = authenticate(request, username=request.POST["username"], password=request.POST["password"])
if user is not None:
login(request, user)
return HttpResponseRedirect(reverse("index"))
else:
return render(request, "app/login.html", {
"message": "Invalid username and/or password."
})
else:
return render(request, "app/login.html")

def logout_view(request):
logout(request)
return HttpResponseRedirect(reverse("index"))

def register(request):
if request.method == "POST":
username = request.POST["username"]
email = request.POST["email"]
# ensure password matches confirmation
password = request.POST["password"]
confirmation = request.POST["confirmation"]
if password != confirmation:
return render(request, "app/register.html", {
"message": "Passwords must match."
})
# attempt to create new user
try:
user = User.objects.create_user(username, email, password)
user.save()
except IntegrityError:
return render(request, "app/register.html", {
"message": "Username already taken."
})
login(request, user)
return HttpResponseRedirect(reverse("index"))
else:
return render(request, "app/register.html")

如果有人知道解决方案,我们将不胜感激!

修复:

def index(request):
return render(request, "app/index.html",{
"username": request.user.username # don't overwriting user
})

您似乎将用户名传递给了user属性,从而覆盖了默认的user对象。

在呈现模板RequestContext时,当前登录的用户(user实例或AnonymousUser实例(存储在模板变量{{user}}中:

来自django文档:此处

问题出在索引方法中

def index(request):
return render(request, "app/index.html",{
"user": User.username
})

更换为

def index(request):
return render(request, "app/index.html")

在模板中,您可以通过{{user.username}}访问登录用户的用户名。因此无需覆盖默认对象

实际上在html中使用user.is_authenticated->request.user.is_authenticated

最新更新