views:

158

answers:

2

I am writing a Player model class in Python with Django, and I've ran into a small problem with the password member. I'd like the password to be automatically hashed upon assignment, but I can't find anything about overloading the assignment operator or anything. Is there any way I can overload the assignment of password so as to automatically do hashlib.md5(password).hexdigest() on it?

from django.db import models

class Player(models.Model):
 name = models.CharField(max_length=30,unique=True)
 password = models.CharField(max_length=32)
 email = models.EmailField()
+6  A: 

Can't you use properties and override setter for the field?

Citing from django documentation:

from django.db import models

class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)

    def _get_full_name(self):
        return "%s %s" % (self.first_name, self.last_name)

    def _set_full_name(self, combined_name):
        self.first_name, self.last_name = combined_name.split(' ', 1)

    full_name = property(_get_full_name)

    full_name_2 = property(_get_full_name, _set_full_name)
krzyk
"Properties" is one of those odd bits of Python terminology that's challenging for newcomers to the language. As Krzyk's example shows you can create "getter" and "setter" functions (and "delete-er" functions as well) and when you bind a class attribute to the results of a call to "property()" (taking getter as a required argument and optional setter, and deleter) ... then all access to that attribute is now mediated by the property functions.
Jim Dennis
A: 

You can use the HashedProperty class that I created for SQLAlchemy. You can use with Django like this:

class Player(models.Model):
    name = models.CharField(max_length=30,unique=True)
    password_hash = models.CharField(max_length=32)
    password_salt = models.CharField(max_length=32)
    password = HashedProperty('password_hash', 'password_salt',
                   hashfunc=salted_hexdigest(hashlib.md5),
                   saltfunc=random_string(32))
    email = models.EmailField()
Ants Aasma