如何检查用户名和密码以进行自定义登录

时间:2019-03-30 17:17:49

标签: python django

models.py

class student(models.Model):

  u_email = models.CharField(max_length=50)
  u_username = models.CharField(max_length=50)
  u_password = models.CharField(max_length=20)

view.py

def login_check(request, *args,**kwargs ):
    if request.method == 'POST':
        c_username= request.POST['username']
        c_password = request.POST['password']
        print(username,password)

我如何执行以下查询以对django中的学生进行认证

"SELECT id FROM student WHERE u_username = c_username and password = c_password"

1 个答案:

答案 0 :(得分:2)

您可以使用django ORM并将其添加到您的代码中:

students = student.objects.filter(u_username=c_username, u_password=c_password)
if students.exists():
    # do whatever you like with list students .e.g: 
    # access to first one id with students[0].id

不记得在视图中添加导入语句

from models import student

def login_check(request, *args,**kwargs ):
    if request.method == 'POST':
        c_username= request.POST['username']
        c_password = request.POST['password']
        students = student.objects.filter(u_username=c_username, u_password=c_password)
        if students:
            print(students[0].id)
            # ...

注意:请不要将密码另存为纯文本。使用哈希函数并保存其输出(请参见this)。您无需知道用户密码。您只想验证传入用户是否知道帐户密码。