How to implement password change form in Django 1.9

£可爱£侵袭症+ 提交于 2019-11-28 05:53:44

问题


The url for my python project is here: https://github.com/abylikhsanov/social

I am trying to implement the password change form, so the user can change his or her password. How can I implement it? The application should keep track of the previous password and should not allow the user to use a previously used password. Also, I want to implement the reset password function.


回答1:


why don't you use django's built-in PasswordChangeForm (django.contrib.auth.forms).

If you like the way it works just use this from, or you can create a new one that inherits PasswordChangeForm

    class PasswordChangeCustomForm(PasswordChangeForm):
        error_css_class = 'has-error'
        error_messages = {'password_incorrect':
                  "Το παλιό συνθηματικό δεν είναι σωστό. Προσπαθείστε   ξανά."}
        old_password = CharField(required=True, label='Συνθηματικό',
                      widget=PasswordInput(attrs={
                        'class': 'form-control'}),
                      error_messages={
                        'required': 'Το συνθηματικό δε μπορεί να είναι κενό'})

        new_password1 = CharField(required=True, label='Συνθηματικό',
                      widget=PasswordInput(attrs={
                        'class': 'form-control'}),
                      error_messages={
                        'required': 'Το συνθηματικό δε μπορεί να είναι κενό'})
        new_password2 = CharField(required=True, label='Συνθηματικό (Επαναλάβατε)',
                      widget=PasswordInput(attrs={
                        'class': 'form-control'}),
                      error_messages={
                        'required': 'Το συνθηματικό δε μπορεί να είναι κενό'})

I will provide later an example of the clean and save methods

see here for more details




回答2:


You can see the Change Password section of following documentation for this. How to change password in Django. It works like this:

  1. Navigation to your project where manage.py file lies

  2. $ python manage.py shell

  3. Execute the following:

    from django.contrib.auth.models import User
    u = User.objects.get(username__exact='john')
    u.set_password('new password')
    u.save()
    

You will have to make a formset and you will perform this action at submission of the form.

You can also use the simple manage.py command:

manage.py changepassword *username*

Just enter the new password twice.

For second part of your question (User cannot choose old password), you can create a table in which you will store user's old password. When user will enter new password, you can check this in that table whether he can choose it or not. Django has a function check_password which is used to compare two passwords.




回答3:


Since you are using you custom user model a nice way to implement the functionality is to create a new form ChangePassword:

class ChangePassword(forms.Form):
      old_password=forms.PasswordField()
      new_password=forms.PasswordField()
      reenter_password=forms.PasswordField()
      def clean(self):
          new_password=self.cleaned_data.get('new_password')
          reenter_password=self.cleaned_data.get('reenter_password')
          #similarly old_password
         if new_password and new_password!=reenter_password or new_password==old_password:
                #raise error
         #get the user object and check from old_password list if any one matches with the new password raise error(read whole answer you would know) 
         return self.cleaned_data #don't forget this.

You can define clean() to check that both passwords match or not, and also the new password entered is not same as the old password.

If you don't want the user to use a password they have used before an option would be

  1. Create a new field (if you want to store these passwords as plain strings)
  2. Create a model containing hashed previous passwords (for better security).

According to your models you are not encrypting passwords so option 1 is good for you. In case you want to encrypt you can choose sha256 for it, library is passlib; just search google.

To implement option 1 just add a field to your model and whenever password is changed, append the old password to this field contents. You can either use a CharField but its maximum length is only 255 instead you can choose textfield, for your model it would be like:

class Members(models.Model):
       #rest fields..
       old_passwords=models.TextField(blank=True,default='')

Now when saving ChangePassword use the cleaned data to update the member password:

def change_password(request):
         if request.method=='POST':
            form=ChangePassword(request.POST)
            if form.is_valid():
                  new_pass=form.cleaned_data['new_password']
                  #get the current user object as user
                  if user.old_password=='':
                         #it's first time user is changing password
                         #populate our Members old_password_field
                         user.old_password=user.password
                  else:         
                         user.old_password=user.old_password+','+user.password
                  user.password=new_password 
                  user.save()
                  #do whatever you want to do man..

The code is just to help you understand what you need to do, you have to do thing your own way!




回答4:


if you take a look at https://github.com/django/django/blob/master/django/contrib/auth/views.py you will notice that

password_reset
takes a named parameter called
template_name
def password_reset(request, is_admin_site=False, 
        template_name='registration/password_reset_form.html',
        email_template_name='registration/password_reset_email.html',
        password_reset_form=PasswordResetForm, 
        token_generator=default_token_generator,
        post_reset_redirect=None):

thus with urls.py like...

from django.conf.urls.defaults import *
from django.contrib.auth.views import password_reset
urlpatterns = patterns('',
 (r'^/accounts/password/reset/$', password_reset, {'template_name': 'my_templates/password_reset.html'}),
 ...

django.contrib.auth.views.password_reset will be called for URLs matching '/accounts/password/reset' with the keyword argument template_name = 'my_templates/password_reset.html'.

i strongly recommend you to go through the following link http://garmoncheg.blogspot.com.au/2012/07/django-resetting-passwords-with.html



来源:https://stackoverflow.com/questions/35256802/how-to-implement-password-change-form-in-django-1-9

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!