首页 > 解决方案 > Django:为什么我的代码让用户使用已被占用的电子邮件地址创建一个新帐户?

问题描述

当我删除以下内容时

user = User.objects.get(username=request.POST['username'])

它会识别用户在注册时是否使用了已获取的电子邮件地址,并向用户显示注册错误。但是,下面的代码不会对使用的电子邮件地址抛出任何错误。我怎样才能解决这个问题?

def signup(request):
 if request.method == "POST":
    # User has info and wants an account now!
    if request.POST['password1'] == request.POST['password2']:
        try:
            user = User.objects.get(username=request.POST['username'])
            email = User.objects.get(email=request.POST['email'])
            return render(request, 'accounts/signup.html', {'error': 'Email and or username has already been taken'})
        except User.DoesNotExist:
            user = User.objects.create_user(request.POST['username'], email=request.POST['email'], password=request.POST['password1'])
            auth.login(request, user)
            return redirect('homepage')
    else:
        return render(request, 'accounts/signup.html', {'error': 'Passwords must match'})
 # User wants to enter info
 return render(request, 'accounts/signup.html')

标签: djangopython-3.xdjango-views

解决方案


请替换except User.DoesNotExist:except ObjectDoesNotExist:使用此链接查看 get() 的 django 定义。

但在此之前,您还需要导入异常:

from django.core.exceptions import ObjectDoesNotExist

推荐阅读