django ValueError当我比较输入值和数据库对象时

gblwokeq  于 2022-12-14  发布在  Go
关注(0)|答案(1)|浏览(149)

我想将表单输入与数据库值进行比较。例如:
有一个名为password的输入字段,我想将输入值与数据库中的密码进行比较(以防我已经知道行(id))
但是当我比较它的时候,我得到了这样的值错误。谷歌了2个小时,什么都没有用。我是django的新手...我希望有人能帮助我:D

下面是我的视图代码

id      = modelUser.objects.values('id').filter(username=txtUsername)
checkPassword = modelUser.objects.values('password').filter(username=txtUsername)

if(txtPassword == checkPassword.password):
    return render(request,'success.html')

Models.py

class modelUser(models.Model):
    firstname = models.CharField(max_length=200, null=False, blank=False)
    lastname = models.CharField(max_length=200, null=False, blank=False)
    username = models.CharField(max_length=200, null=False, blank=False)
    password = models.CharField(max_length=200, null=False, blank=False)
    def __str__(self):
        return self.username
jv4diomz

jv4diomz1#

首先,我想说的是阅读Django文档,了解如何替换自定义用户模型和如何登录用户。
我会重复我的话,并强调我推荐这种方法,请按照框架教程学习如何使用它的全部功能。
为了学习,你会这样做:
views.py:

from django.core.exceptions import ObjectDoesNotExist
from django.shortcuts import render
from core.models import modelUser

def alternative_login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')

        try:
            user = modelUser.objects.get(username=username)
            if password == user.password:
                return render(request, 'alternative_success.html')
        except ObjectDoesNotExist:
            pass

    return render(request, 'alternative_login.html', {})

urls.py

from django.urls import path
from core import views

app_name = 'core'

urlpatterns = [
    path('alternative/login/', views.alternative_login, name='alternative-login'),
]

alternative_login.html

{% extends 'base.html' %}

{% block content %}
<form action="{% url 'core:alternative-login' %}" method="post">
    {% csrf_token %}
    <input type="text" name="username">
    <input type="password" name="password">
    <button type="submit">Submit</button>
</form>
{% endblock %}

相关问题