need help on set_password()..............

157 views
Skip to first unread message

yaswanth s

unread,
Jul 28, 2012, 10:14:52 PM7/28/12
to django...@googlegroups.com
hi every one,
                  i created one external registration form.. all are working good, but when we open the admin sit it showing the password as plain text. how to convert the password into hash formate and save into database.. can any one suggest for the abovt one................


--
Thanks in advance 
yaswanth

Chris Lawlor

unread,
Jul 29, 2012, 12:24:08 PM7/29/12
to django...@googlegroups.com
If you're using the User model from contrib.auth, you can simply use User.objects.create_user(username, email=None, password=password). This will create a new User object, and then call set_password()

# forms.py
class RegistrationForm(form.Form):
    username = forms.CharField()
    password = forms.CharField(widget=PasswordInput)

# views.py
def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            # UserManager.create_user() is a convenience method for creating a new user, and calling user.set_password()
            user = User.objects.create_user(form.cleaned_data['username''], password=form.cleaned_data['password'])
    else:
        form = RegistrationForm()
    return render(request, 'your_template.html', {'form': form})

If you're not using Django's User model, you could use one of the password hashers from contrib.auth.hashers to create the hashed version of the user's password. Something like:


class MyUser(models.Model):
    username = models.CharField(...)
    password = models.CharField(max_length=128)

# views.py

from django.contrib.auth.hashers import PBKDF2PasswordHasher as hasher

def register(request):
    ...
    user = MyUser.objects.create(username=form.cleaned_data['username'], commit=False)
    salt = hasher.salt()
    user.password = hasher.encode(form.cleaned_data['password'], salt)
    user.save()


Or better yet, move the user creation logic into a manager, similar to the design of UserManager:

class MyUserManager(models.Manager):
    def create_user(self, username, password):
        user = self.model.create(username, commit=False)
        salt = hasher.salt()
        user.password = hasher.encode(password, salt)
        return user

class MyUser(models.Model):
    ...
    objects = MyUserManager()

With that, you can do user = MyUser.objects.create_user(username, password).

Looking at the source code for contrib.auth.models and contrib.auth.hashers may prove helpful.


If you have existing password data that you need to convert to a hashed format, you might consider using a South data migration. Conveniently, the tutorial on data migrations uses this use case as an example: http://south.readthedocs.org/en/latest/tutorial/part3.html#data-migrations.

(Consider all code to be untested pseudo-code)
Reply all
Reply to author
Forward
0 new messages