django - 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')
解决方案
请替换except User.DoesNotExist:
为except ObjectDoesNotExist:
。使用此链接查看 get() 的 django 定义。
但在此之前,您还需要导入异常:
from django.core.exceptions import ObjectDoesNotExist
推荐阅读
- api - Apicurio 注册表 - 工件的文档选项卡为空
- angular - NgRx EffectsModule 导入组
- swift - CollectionView 第一个和最后一个单元格保持选中状态
- javascript - 'keypress' 上的 Object.values 过滤器
- html - 需要 Rally HTML 返回 url 而不是字符串作为附件
- boost - 尝试访问 dynamic_bitset 中的私有成员
- goroutine - goroutine 中的 http.Client
- sql - T-SQL 语法:“LIKE '%'”合法吗?
- php - Codeigniter curl how to send CSRF token?
- javascript - Nodejs:使用异步等待语法通过http将文件下载到字符串中