def profile(request):
Exist_Emails = User.objects.filter(is_active=True).values_list('email', flat=True)
Exist_Usernames = User.objects.filter(is_active=True).values_list('username', flat=True)
current_user = User.objects.get(username=request.user.username)
Email_Invalid = False
Username_Invalid = False
if request.method != 'POST':
u_form = UserUpdateForm(instance=request.user)
p_form = ProfileUpdateForm(instance=request.user.profile)
else:
update_username = request.POST.get('username')
u_form = UserUpdateForm(request.POST, instance=request.user)
p_form = ProfileUpdateForm(request.POST,
request.FILES,
instance=request.user.profile)
if u_form.is_valid() and p_form.is_valid():
p_form.save()
update_u_form = u_form.save(commit=False)
#Problem occurs in this if statement!
if update_u_form.username in Exist_Usernames and update_u_form.username != current_user.username:
Username_Invalid = True
u_form = UserUpdateForm(instance=current_user) ##
messages.error(request, 'The username already eixts')
#But it worked in this elif statement which is almost the same!
elif update_u_form.email in Exist_Emails and update_u_form.email != current_user.email:
Email_Invalid = True
u_form = UserUpdateForm(instance=current_user)
messages.error(request, 'The email already exits.')
else:
update_u_form.save()
return redirect('/users/profile/')
context = {
'u_form': u_form, 'p_form': p_form,'update_username':
update_username,'Email_Invalid': Email_Invalid,'current_user':
current_user, 'Username_Invalid': Username_Invalid}
return render(request, 'users/profile.html', context)
这是html模板:
{% if Email_Invalid == "True" or Username_Invalid == "True" %}
{{ current_user.username }}
</div>
<div style="font-size:16px;">
{{ current_user.email }}
</div>
<p>"Sorry, the email or username already exits."</p>
{% else %}
{{ user.username }}
</div>
<div style="font-size:16px;">
{{ user.email }}
</div>
{% endif %}
{{Username_Invalid}}
{{update_username}}
<form method="post" class="form" enctype="multipart/form-data">
{% csrf_token %}
{{ u_form.as_p }}
{{ p_form.as_p }}
<button name="sumbit" class="btn btn-primary" >Update</button>
</form>
我的forms.py:
class UserUpdateForm(forms.ModelForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email']
当我键入更新的用户名时,然后按提交。但是{{Username_Invalid}}
返回False
,在if语句中应该为True。
然后我检查了{{update_username}}
,它返回了NONE
!这里的update_username只是request.POST.get('username')。
这是怎么回事?我认为UserUpdateForm
应该继承自User模型。因此request.POST
应该有一个字典键值对'username':username
。
我的调试过程:
我想做的是当用户尝试编辑电子邮件或用户名,但其他人已经在数据库中注册了这些电子邮件或用户名时,在u_form中显示(instance = current_user)
。
它在电子邮件字段中工作得很好,但是当我编辑另一个用户已经注册的用户名时,实例将显示我键入的内容(它应打印instance = current_user
而不是request.user )。
因此我发现执行此操作时,它没有输入is_valid
之后的第一个IF语句,因为Username_Invalid
仍显示False
。然后我检查'update_u_form.username
'是否有问题,所以我设置了
update_username = request.POST.get('username')
打印出该值,并返回NONE
。我认为这是问题所在,但无法弄清原因。