I’m building a student management system, but there’s a problem. When I register a new user, i enter it’s username, first name, last name, etc… and password of course. But when I save the form and insert the user in the database, the password is stored as plain text and not hashed. On the other hand, when I create user thru django admin panel the user password i hashed normally and login works…
Here is my code:
views.py
def addUser(request):
if request.method == 'GET':
form = AddNewUserForm()
return render(request, 'addNewUser.html', {'form': form})
if request.method == 'POST':
form = AddNewUserForm(request.POST)
if form.is_valid():
password = make_password(form.cleaned_data['password'])
form.password = password
form.save(make_password(form.cleaned_data['password']))
print("New user added!")
return render(request, 'addNewUser.html', {'form': form})
return redirect('/users/')
.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form method="POST">
{{form}}
{% csrf_token %}
<input type="submit" value="Add new user">
</form>
</body>
</html>
>Solution :
The issue you’re facing is that the password is being stored as plain text in the database instead of being hashed. Django provides built-in functionality to handle password hashing, but it seems that you’re missing that part in your code.
To ensure that the user’s password is hashed before storing it in the database, you need to make a small adjustment in your code. Here’s an updated version of your views.py file:
def addUser(request):
if request.method == 'GET':
form = AddNewUserForm()
return render(request, 'addNewUser.html', {'form': form})
if request.method == 'POST':
form = AddNewUserForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.password = make_password(form.cleaned_data['password']) # Hash the password
user.save()
print("New user added!")
return render(request, 'addNewUser.html', {'form': form})
In the updated code, the make_password() function from django.contrib.auth.hashers is used to hash the password before saving it. The commit=False argument is used when calling form.save() to create the user instance but not save it to the database yet. Then, the hashed password is assigned to the user.password field, and finally, the user is saved to the database.
By incorporating this change, the user’s password will be securely hashed before being stored in the database, just like when creating users through the Django admin panel.