[Solved]-How to generate HASH for Django model


Don’t call the _createHash() function in your field, but just pass the reference to the callable in your model, e.g.

hash_1 = models.CharField(max_length=10,default=_createHash,unique=True)

As Lennart Regebro mentioned in his answer, you’ll get the same value for each time you start the server in your attempt.

The Django docs say this about it:


The default value for the field. This can be a value or
a callable object. If callable it will be called every time a new
object is created.


_createHash() is called when you define the model, so you have the same default every time you create a new object.

You can look at creating the hash in the save() method of the model, that’s probably the easiest.

Leave a comment