42. Changing logged in account data and password
@login_required
def your_account(request):
error = None
altered_account = False
altered_password = False
if request.method == 'POST':
data = request.POST.dict()
#? email and password are outside to diferentiate what forms is submitted
if data.get('current_password'):
#? is modifying the password
current_password = data.get("current_password")
new_password = data.get("new_password")
confirm_new_password = data.get("confirm_new_password")
if current_password != new_password and confirm_new_password != current_password:
if secure_password(new_password) :
if new_password == confirm_new_password :
#? verify current password
user = authenticate(request, username=request.user.email, password=current_password)
if user:
#? correct password, change password
user.set_password(new_password)
user.save()
altered_password = True
else :
error = "invalid_current_password"
else :
error = "different_passwords"
else :
error = "weak_password"
else :
error = "same_password"
elif data.get("email") :
#? is modifying the account data
email = data.get("email")
phone = data.get("phone")
name = data.get("name")
if email != request.user.email :
users = User.objects.filter(email=email)
if len(users) > 0 :
error = "email_exists"
if not error :
client = request.user.client
client.email = email
request.user.username = email
request.user.email = email #? also changing from the user, they are different things
client.name = name
client.phone = phone
client.save()
request.user.save()
altered_account = True
else :
error = "invalid_changes"
context = {"error" : error, "altered_account" : altered_account, "altered_password" : altered_password}
return render(request, 'user/your_account.html', context) 
Last updated