qq_39376614
qq_39376614
采纳率0%
2020-03-23 21:59 阅读 489

Django 写的登陆功能,当我登陆时,form.is_valid() 总是返回false,并提示用户名已存在

5

models.py代码:

from django.db import models

class User(models.Model):
    account = models.CharField(max_length=255, primary_key=True)
    passwd = models.CharField(max_length=255)

    def __str__(self):
        return self.account

    class Meta:
        db_table = "user"

form.py代码:

from django import forms

from user.models import User


class UserForm(forms.ModelForm):
    account = forms.CharField(label='账号', required=True)
    passwd = forms.CharField(label='密码', widget=forms.PasswordInput(), required=True)

    class Meta:
        model = User
        fields = {'account', 'passwd'}

登陆代码段:

def login(request):
    if request.method == 'POST':
        form = UserForm(request.POST)  # 关联前端表单数据 和 后台表单类
        if form.is_valid():  # 验证表单数据是否合法
            account = form.cleaned_data['account']
            passwd = form.cleaned_data['passwd']
            user = User.objects.filter(account=account)
            if user:
                if check_password(passwd, user.passwd):
                    return HttpResponse('登陆成功!')
                else:
                    return HttpResponse('密码错误!')
            else:
                return HttpResponse('用户不存在!')
        else:
            return HttpResponse(str(form.errors))
    else:
        form = UserForm()
        return render(request, 'user/login.html', {'form': form})

注册代码段:

def register(request):
    if request.method == 'POST':
        user = User()
        form = UserForm(request.POST)
        if form.is_valid():
            pwd = form.cleaned_data['passwd']
            user = form.save(commit=False)
            user.passwd = make_password(pwd, None, 'pbkdf2_sha256')
            user.save()
            return HttpResponse('注册成功!')
        else:
            return HttpResponse(str(form.errors))
        # try:
        #     user.save(force_insert=True)
        # except IntegrityError:
        #     return HttpResponse('账号重复!')
        # return HttpResponse('注册成功!')
    else:
        form = UserForm()
        return render(request, 'user/register.html', {'form': form})

当我登陆时, form.is_valid() 会显示false,无法进入到保存数据库的代码段中。并且 form.errors 会显示如下信息。

图片说明

我估计是它把我的这一步理解成要新建数据了,但是我的登陆代码里完全没有与save有关的代码。而且程序在运行到 form = UserForm(request.POST) ,但还有没有到 form.is_valid() 的时候,就可以发现这个错误已经出现了。不知道是为什么。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • caozhy 从今以后生命中的每一秒都属于我爱的人 2020-03-23 23:52
  • qq_38175040 336699强强 2020-03-28 20:27

    def check_login(request):
    if request.method == "POST":
    username = request.POST.get('userName', None)
    password = request.POST.get('passWord', None)
    message = "所有字段都必须填写!"
    #if username =='admin' and password =='123456':///此处试验成功,成功从表单处得到输入的用户名和密码
    # return redirect('homepage')
    #else:
    # return render(request, 'register.html')
    if username and password: # 确保用户名和密码都不为空
    username = username.strip()
    try:
    user = models.User.objects.get(name=username) #查看user表中是否有用户名与前端表单中输入的一样
    if user.password == password:
    models.User.objects.filter(name=username).update(login_num=user.login_num+1) #登录成功,则表中字段login_num+1,表示登录次数加一
    user_name = user.name
    request.session['user_name'] = user_name
    user_id = user.id
    request.session['user_id'] = user_id
    total_login = user.login_num
    request.session['total_login'] = total_login
    total_users_num = models.User.objects.count()
    request.session['total_users_num'] = total_users_num
    request.session['password'] = user.password
    return render(request, 'homepage.html', {"user_name": user_name,"user_id":user_id,"total_login":total_login,"total_users_num":total_users_num})
    else:
    message = "密码不正确!"
    except:
    message = "用户名不存在!"
    return render(request, 'login.html', {"message": message})
    return render(request, 'login.html')

    
    

    给段参考代码,我是从前端的表单中获取输入的用户名和密码,然后与models中创建的user表对比

    点赞 评论 复制链接分享

相关推荐