【发布时间】:2018-09-24 16:35:04
【问题描述】:
抱歉,如果这很简单或我的术语不正确,这是我的第一个 django 项目。我无法在网上找到类似的解决方案。
我有一个现有的应用程序,其中包含一个我对用户进行身份验证的 postgres 数据库。我在 Django 中编写了一个应用程序来与一些表交互并向用户显示信息。我想使用 Django 登录和跟踪用户会话。所以我可以使用像
这样的功能{% if user.is_authenticated %}
但我不想使用 migrate 命令,所以我不想更改现有数据库。我可以访问帐户信息所在的表,因为我为它创建了一个模型。
我看到您可以使用远程用户登录参数,但我找不到任何有关如何使用它的示例或指南,我完全迷路了。
现在我在视图页面中创建了一个登录表单。然后获取输入的用户名和密码,但是不知道接下来要做什么。还需要散列密码。 djano 中是否有一个库可以为应用程序执行此操作。
对此的任何指针或在线指南将不胜感激。
这里是登录视图
if request.method == "POST":
form = LoginForm(request.POST)
if form.is_valid():
email = form.data['account_email']
password = form.data['account_password']
user = authenticate(username=email)
if user.check_password(password):
login(request, user)
return redirect('myapp:cust_select')
else:
# Username and password did not match
raise ValidationError('Invalid Username/Password')
return render(request, 'myapp/login.html', {'form' : form}
后端.py
from django.conf import settings
from django.contrib.auth import get_user_model
class UserAuthBackend(object):
def authenticate(self, username=None, password=None):
try:
account = get_user_model()
user = account.objects.get(account_email=username)
if user:
return user
except account.DoesNotExist:
print "account not found"
return None
def get_user(self, user_id):
try:
account = get_user_model()
return account.objects.get(pk=user_id)
except User.DoesNotExist:
return None
models.py
class Accounts(AbstractUser):
account_id = models.AutoField(primary_key=True)
account_email = models.CharField(max_length=100)
account_password = models.CharField(max_length=20)
def __str__(self):
return self.account_email
class Meta:
managed = False
db_table = 'accounts'
settings.py
AUTHENTICATION_BACKENDS = ( 'myapp.backends.UserAuthBackend', )
它在 sql 查询中不断退出并出现相同的错误。 列accounts.password 不存在 第 1 行:选择 "accounts"."password", "accounts"."last_login", "acco...
它似乎没有使用我的帐户模型。它确实从该表中选择了它,但我怎样才能让它停止请求 accounts.password 和 accounts.last_login,因为它们在 y Accounts 模型中不存在
【问题讨论】:
-
当表单有效时,您应该使用其
cleaned_data字典而不是data字典获取数据。另外我假设密码不是以纯文本形式保存在您的数据库中,而是经过哈希处理,因此您不能仅使用account_password=password获取帐户(Django 有一个authenticate方法来计算哈希值并检查保存在分贝)。 -
但我认为如果用户数据保存在不是用 Django 创建的数据库中,直接在 Django 中进行身份验证会很困难。 authentication backend mechanism of Django 允许您通过编写自己的身份验证后端来调用外部 API 来验证您的用户,这可能会更容易(假设您已经有一个可以根据用户名/密码对用户进行身份验证的服务器)。
标签: python django authentication