我正在尝试使用自定义用户模型执行django身份验证。请注意,这是针对学校项目而不是
我有以下用户模型
class User(AbstractBaseUser):
userID = models.AutoField(primary_key=True)
username = models.CharField(max_length=20, unique=True)
password = models.CharField(max_length=24)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=50)
USERNAME_FIELD = "username"
REQUIRED_FIELDS = ["first_name", "last_name"]
def get_full_name(self):
return self.first_name + " " + self.last_name
def get_short_name(self):
return self.username
class Meta:
db_table = "User"
app_label = "funbids"
managed = False
我在settings.py中定义了我的模型
AUTH_USER_MODEL = 'funbids.User'
我也在使用自定义身份验证后端。请注意,这只是使用明文密码的测试(我知道在任何生产环境中这都是一个糟糕的想法)。我正在使用自定义身份验证后端,因为此应用程序的要求是使用原始SQL查询与现有数据库进行身份验证。
class AuthBackend(object):
"""
Authenticate a user in funbids
"""
def authenticate(self, request, username=None, password=None):
# Test credentials
cursor = connections["funbids"].cursor()
cursor.execute("SELECT 1 FROM User WHERE username=%s AND password=%s", [username, password])
if cursor.fetchone():
# Have to grab the model, then authenticate
user = User.objects.get(username=username)
return user
else:
return None
def get_user(self, user_id):
try:
return User.objects.get(username=user_id)
except User.DoesNotExist:
return None
一切似乎都在我的登录视图中有效。
def login_user(request, login_failed=False):
# Redirect the user to the index if they're already authenticated and arrive at the login page
if request.user.is_authenticated:
return redirect("funbids:index")
# Get the username and password from POST data
username = request.POST.get("username", "")
password = request.POST.get("password", "")
next = request.POST.get("next", "")
# Attempt to authenticate the user if both a username and password are present
if username and password:
log.debug("User %s requesting login" % username)
# Test credentials
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
log.debug("authenticated user is: %s" % request.user)
request.session.set_expiry(46800)
else:
login_failed = True
if request.user.is_authenticated:
# Authentication succeeded. Send the user to the original page they requested
# using the the "next" POST data or the index.
log.debug("Successfully authenticated user %s" % request.user)
if next:
return redirect(next)
else:
return redirect("funbids:index")
else:
# Failed authenticate, send back to login page
log.debug("Failed to authenticate user %s" % username)
# No credentials present/user failed auth - just load the page and populate the "next" form input
# in case the user was redirected here from a view they couldn't access unauthenticated.
next = request.GET.get("next", "")
try:
template = loader.get_template("funbids/login.html")
except TemplateDoesNotExist:
raise Http404("Page Not Found")
context = {
"pagetitle": "Welcome to FunBids!",
"next": next,
"login_failed": login_failed,
"template": template,
"request": request,
}
# Return the rendered page for display.
return render(request, template_name="funbids/page.html", context=context)
debug语句完美打印我们的用户名,例如:
[DEBUG] Successfully authenticated user adam
无论其
一旦我切换到另一个视图,我就不再登录了。相反,我是一个匿名用户,例如:
def search(request):
log.debug("request user is: %s" % request.user)
try:
template = loader.get_template("funbids/search.html")
except TemplateDoesNotExist:
raise Http404("Page Not Found")
context = {
"pagetitle": "Search items for sale",
"template": template,
"request": request,
}
# Return the rendered page for display.
return render(request, template_name="funbids/page.html", context=context)
这次调试语句打印出来:
[DEBUG] request user is: AnonymousUser
我已经对这个问题进行了一些阅读,并发现当用户进行身份验证但未登录时会发生这种情况。但是,我可以成功登录而没有任何问题,所以我不确定发生了什么。
感谢任何帮助......谢谢。
答案 0 :(得分:0)
事实证明问题非常微妙。 Django无法获取我的用户,因为我的authuser方法在我的auth后端中出错了。
return User.objects.get(username=user_id)
应该是
return User.objects.get(userID=user_id)
因为“userID”字段是主键。