Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate HASH for Django model

Tags:

python

django

I am trying to generate unique HASH values for my Django models of 10 digit i have tried these methods but i am getting this error

return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: column hash_3 is not unique

Here what i have tried :

import os
import time
import hashlib
from os import path
from binascii import hexlify
from django.db import models
from django.contrib import admin
from django.core.files.storage import FileSystemStorage
#------------------------------------------------------------------------------ 

def _createHash():
    """This function generate 10 character long hash"""
    hash = hashlib.sha1()
    hash.update(str(time.time()))
    return  hash.hexdigest()[:-10]


class tags(models.Model):
    """ This is the tag model """

    seo_url1 = models.URLField()
    seo_url2 = models.URLField()
    seo_url3 = models.URLField()
    tagDescription = models.TextField()                 # Tag Description
    tag = models.CharField(max_length=200)              # Tag name
    tagSlug = models.CharField(max_length=400)          # Extra info can be added to the existing tag using this field
    updatedAt = models.DateTimeField(auto_now=True)     # Time at which tag is updated
    createdAt = models.DateTimeField(auto_now_add=True) # Time at which tag is created
    hash_1 = models.CharField(max_length=10,default=_createHash(),unique=True)
    hash_2 = models.CharField(max_length=10,default=_createHash(),unique=True)
    hash_3 = models.CharField(max_length=10,default=_createHash(),unique=True)

I have also tried this method:

def _createHash():
    """This function generate 10 character long hash"""
    return hexlify(os.urandom(5))

I have a script which inserts data into this model every time i run my script i got above mentioned error ..is there any other way of doing this..i want to store unique hash values into columns hash_1,hash_2,hash_3.

like image 841
Vaibhav Jain Avatar asked May 31 '13 09:05

Vaibhav Jain


People also ask

What is Django hash?

By default, Django uses the PBKDF2 algorithm with a SHA256 hash, a password stretching mechanism recommended by NIST. This should be sufficient for most users: it's quite secure, requiring massive amounts of computing time to break.

Does Django auto generate ID?

Thus, an id AutoField that auto increments on every instance of that model is created by default when you run makemigrations on the project.

What is Foreignkey Django models?

Introduction to Django Foreign Key. A foreign key is a process through which the fields of one table can be used in another table flexibly. So, two different tables can be easily linked by means of the foreign key. This linking of the two tables can be easily achieved by means of foreign key processes.


2 Answers

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:

Field.default

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.

like image 83
gertvdijk Avatar answered Sep 19 '22 08:09

gertvdijk


_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.

like image 26
Lennart Regebro Avatar answered Sep 20 '22 08:09

Lennart Regebro