Django-针对现有数据库进行身份验证 [英] Django - Authenticate against existing DB

查看:66
本文介绍了Django-针对现有数据库进行身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Apologies if this is simple or my terminology is off, this is my first django project. I haven't been able to find a similar solution for this online.

我有一个现有的应用程序,带有一个Postgres DB,可在其中验证我的用户身份.我已经在Django中编写了一个应用程序,可以与一些表进行交互并向用户显示信息.我想使用Django登录和跟踪该数据库的用户会话.所以我可以使用

I have an existing application, with a postgres DB where I authenticate my users. I have wrote an application in Django to interact with some tables and display info to the user. I would like to use Django to login and track User sessions against this DB. so I can use the features like

{%,如果user.is_authenticated%}

但是我不想使用migration命令,所以我不想更改现有的数据库.创建模型时,我可以访问帐户信息所在的表.

but I don't want to use the migrate command so I don't want to change the existing DB. I can access the table where the account info is as I created a model for it.

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

I see you can use remote user logon param but I cant find any sample or guide on how to use it and am completely lost.

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

Right now I create a login form in the views page. Then get the username and password that is entered, but I don't know what to do next. Also would need to hash the password. Is there a libray in djano that will do that for the app.

任何指针或在线指南,将不胜感激.

Any pointers or online guides for this would be appreciated.

这是登录视图

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}

backends.py

backends.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

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

settings.py

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

它会不断退出,并在sql查询中出现相同的错误.列accounts.password不存在第1行:选择帐户".密码",帐户"."last_login",帐户...

Its keeps exiting with the same error in the sql query. column accounts.password does not exist LINE 1: SELECT "accounts"."password", "accounts"."last_login", "acco...

它似乎没有使用我的帐户模型.它确实从该表中选择了它,但是我该如何停止请求 accounts.password accounts.last_login ,因为它们在y Accounts模型中不存在

It doesnt appear to be using my Account model. It does select it from that table but how can i get it to stop requesting accounts.password and accounts.last_login as they dont exist in y Accounts model

推荐答案

对于参考注意:您需要尝试一下才能使此代码正常工作

For reference Note: You need to do try, catch to get this code working

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})

这篇关于Django-针对现有数据库进行身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆