Change a user’s password in Django, and check that the data provided is correct

Asked

Viewed 417 times

0

I am working on a project in Django for didactic purposes and I am having trouble changing user password in Django.

However I already managed to change the password through a form as below:

These are my views:

def password(request):
   if request.method == 'POST':
   username = request.POST.get('username')
   email = request.POST.get('email')
   novasenha = request.POST.get('novasenha')

       user = User.objects.get(username=username)
       user.set_password(novasenha)
       user.save()
       messages.success(request,'Senha alterada com sucesso!')
   else:
       messages.success(request, 'Dados errados')
       return render(request,'password_form.html')

return render(request,'password_form.html')

This is my form, where the views take the values:

<div class="container">
    <form method="POST">
        {% csrf_token %}
        <label>Usuário</label>
        <input type="text" name="username"><br>
        <br>
        <label>E-mail</label>
        <input type="email" name="email"><br>
        <br>
        <label>Nova Senha</label>
        <input type="password" name="novasenha"><br>
        <br>
    <button type="submit">SALVAR</button>
    </form>
</div>

So, I change the user password, but I do not check if the data is correct, how can I implement it? thanks!

1 answer

1

To check if the user exists you can use Try:

try:
    user = User.objects.get(username=username)
except user.DoesNotExist:
    messages.success(request, 'Dados errados')
    return render(request,'password_form.html')
  • Thank you so much for your help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.