python - Django - 针对现有数据库进行身份验证

标签 python django authentication

抱歉,如果这很简单或者我的术语不正确,这是我的第一个 django 项目。我在网上找不到类似的解决方案。

我有一个现有的应用程序,带有一个 postgres 数据库,我可以在其中对我的用户进行身份验证。我在 Django 中编写了一个应用程序来与一些表交互并向用户显示信息。我想使用 Django 登录并跟踪此数据库的用户 session 。所以我可以使用像

这样的功能

{% if user.is_authenticated %}

但我不想使用迁移命令,所以我不想更改现有的数据库。当我为其创建模型时,我可以访问其中包含帐户信息的表。

我看到您可以使用远程用户登录参数,但我找不到任何有关如何使用它的示例或指南,并且完全迷失了。

现在我在 View 页面中创建一个登录表单。然后获取输入的用户名和密码,但我不知道下一步该怎么做。还需要对密码进行哈希处理。 djano 中是否有一个库可以为应用程序执行此操作。

对此的任何指示或在线指南将不胜感激。

这是登录 View

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

模型.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'

设置.py

 AUTHENTICATION_BACKENDS = ( 'myapp.backends.UserAuthBackend', )

它不断退出并在 sql 查询中出现相同的错误。 列 account.password 不存在 第 1 行:选择“帐户”.“密码”、“帐户”.“last_login”、“帐户...

它似乎没有使用我的帐户模型。它确实从该表中选择它,但我怎样才能让它停止请求 accounts.passwordaccounts.last_login 因为它们不存在于 y 帐户模型

最佳答案

对于reference 注意:您需要尝试、捕获才能使此代码正常工作

def login(request):
    form = LoginForm()

    if request.method == "POST":
    form = LoginForm(request.POST)
        if form.is_valid():
            username = form.data['account_email']
            password = form.data['account_password']

            # First authenticate
            user = authenticate(request, username=username, password=password)

            if user is not None  :
                # Succeed, now log user in
                login(request,user)
                return redirect('myapp:select')
            else:
                # Username and password did not match
                raise ValidationError('Invalid Username/Password')

     return render(request, 'myapp/login.html', {'form' : form})

关于python - Django - 针对现有数据库进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52483763/

相关文章:

python - 如何在 HTML 中嵌入 python 文件或代码?

python - python中基于geo查询cloudant数据库的建议

django - 如何在新项目中开发/包含 Django 自定义可重用应用程序?有一些指导方针吗?

php - 如何使用 PHP 发送持久性 "Authorization" header

api - 在 .net core web api 中存储 JWT token 的位置?

python - 使用 nlp 从句子中挑选主语 + 形容词对

python - 递归向 zss 树添加节点

Django Rest Framework 将用户数据 View 限制为管理员和自己的用户

python - 包含来自多个模型的字段的表单

authentication - OpenID 身份验证如何工作?