我是Django Python的新手,在注册过程中遇到此奇怪的错误。
请让我知道我在哪里做错了。
这是我在views.py中的代码:
if request.method=='POST':
#SignUp
if request.POST['password1'] == request.POST['password2']:
try:
user = User.objects.get(username = request.POST.get('username1'))
return render(request, 'accounts/signup.html', {'error':'username is already taken'})
except User.DoesNotExist:
user = User.objects.create_user(username=request.POST['username1'], password=request.POST['password'])
auth.login(request, user)
return redirect('home')
else:
#enter info
return render(request, 'accounts/signup.html')
如果我输入user= request.POST.get('username1')
,无论输入什么内容,我都会收到“用户名已被占用”消息。
我的html代码:
<form method="POST" action="{% url 'signup' %}" class="form" autocomplete="off">
{% csrf_token %}
<div class="form__group">
<input type="text" placeholder="username" name="username1" class="form__input" id="username1" autocomplete="off"/>
</div>
<div class="form__group" autocomplete="off">
<input type="email" placeholder="email" name="email" class="form__input" autocomplete="off"/>
</div>
<div class="form__group">
<input type="password" placeholder="Password" name="password1" class="form__input" />
</div>
<div class="form__group">
<input type="password" placeholder="Confirm Password" name="password2" class="form__input" />
</div>
<input class="btn btn-primary" type="submit" value="signup!"/>
</form>
错误是:
MultiValueDictKeyError at /accounts/signup/
'password'
Request Method: POST
Request URL: http://127.0.0.1:8000/accounts/signup/
Django Version: 2.2.9
Exception Type: MultiValueDictKeyError
Exception Value:
'password'
Exception Location: C:\Users\HP\Desktop\django\zakevenv\lib\site-packages\django\utils\datastructures.py in __getitem__, line 80
Python Executable: C:\Users\HP\Desktop\django\zakevenv\Scripts\python.exe
Python Version: 3.7.4
Python Path:
['C:\\Users\\HP\\Desktop\\django\\producthunt-project',
'C:\\Users\\HP\\Desktop\\django\\zakevenv\\Scripts\\python37.zip',
'C:\\Users\\HP\\Desktop\\django\\zakevenv\\DLLs',
'C:\\Users\\HP\\Desktop\\django\\zakevenv\\lib',
'C:\\Users\\HP\\Desktop\\django\\zakevenv\\Scripts',
'C:\\Users\\HP\\Anaconda3\\Lib',
'C:\\Users\\HP\\Anaconda3\\DLLs',
'C:\\Users\\HP\\Desktop\\django\\zakevenv',
'C:\\Users\\HP\\Desktop\\django\\zakevenv\\lib\\site-packages']
Server time: Thu, 23 Jan 2020 15:20:06 +0000
我已经花了几个小时,但我仍然不知道我在哪里做错了:(。 任何帮助将不胜感激。
答案 0 :(得分:1)
if request.method=='POST':
#SignUp
if request.POST['password1'] == request.POST['password2']:
try:
user = User.objects.get(username = request.POST.get('username1'))
return render(request, 'accounts/signup.html', {'error':'username is already taken'})
except User.DoesNotExist:
user = User.objects.create_user(username=request.POST['username1'], password=request.POST['password1'])
auth.login(request, user)
return redirect('home')
else:
#enter info
return render(request, 'accounts/signup.html')
错误::如果您查看try块,则尝试获取用户名,则此用户名没有执行任何操作,然后在render方法中,您通过分配信息来发送错误消息。因此,在模板文件上它会显示错误消息,因为您将其作为默认消息发送。