'How to update password in django?

I want to edit my user data from template, bellow are my codes.

def guru_edit(request, id):
   Guru = get_object_or_404(DataGuru, GuruUser_FK_id=id)
   GuruUser = get_object_or_404(User, id=id)
   if request.method == 'POST':
       form_guru = dataguruform(request.POST, instance=Guru)
       form_user = userform(request.POST, instance=GuruUser)
       if form_guru.is_valid() and form_user.is_valid():
           form_guru.save()
           form_user.save()
           return redirect('index_guru')
   else:
       form_guru = dataguruform(instance=Guru)
       form_user = userform(instance=GuruUser)
  return render(request, 'guru/guru_tambah.html', {'form_user': form_user,'form_guru':form_guru})

this is my forms.py

class userform(ModelForm):
    class Meta:
       model = User
       fields = ('username','email', 'password','is_staff','is_active','is_superuser')
    widgets={
    'password':TextInput(attrs={'type':'password'})
    }

But when i was save from template, the password is not encrypted like it used to be, but just plaintext. How to make it encripted?



Solution 1:[1]

Do not set the password via a form field. Set the password with User.set_password() method which accepts your unencrypted password:

user_form = UserForm(request.POST, instance=user)
if user_form.is_valid():
    user = user_form.save()
    user.set_password('unencrypted_password')  # replace with your real password
    user.save()
    return redirect('index_guru')

I have named the variables and forms in a bit more Django-ish way here, as you can see.

Background: The password in Django is stored as a (most commonly PBKDF2) hash in your database. set_password takes care of seeking the correct hashing method and salting and hashing your passwords correctly.

Forms should merely contain something like password and password_check fields that are used to check if your user inputs his or her password correctly. They should not be used to save a plain password into your database, which I suspect is happening here by default.

You can use set_password inside your forms as well by overriding the UserForm.save() method.

Take the time to read through this document:

https://docs.djangoproject.com/en/dev/topics/auth/passwords/

Solution 2:[2]

Just create a view using Django's built in forms and views:

In your views.py:

from django.contrib.auth.views import PasswordChangeView
from django.contrib.auth.forms import PasswordChangeForm

class UpdatePassword(PasswordChangeView):
    form_class = PasswordChangeForm
    success_url = '/user/edit-profile'
    template_name = 'app/change-password.html'

Inside your urls.py:


from . import views

urlpatterns = [
path('/change-password', views.UpdatePassword.as_view(), name="update_password"),
]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Josh Martin