5

Could someone please help me create a field in my model that generates a unique 8 character alphanumeric string (i.e. A#######) ID every time a user makes a form submission?

My models.py form is currently as follows:

from django.db import models
from django.contrib.auth.models import User

    class Transfer(models.Model):
        id = models.AutoField(primary_key=True)
        user = models.ForeignKey(User)
        timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)

I have looked at pythons UUID feature but these identifiers are quite long and messy compared with what I am looking to generate.

Any help would be hugely appreciated!

user2798841
  • 291
  • 1
  • 4
  • 15

5 Answers5

0

Something like this:

''.join(random.choice(string.ascii_uppercase) for _ in range(8))
jujka
  • 1,190
  • 13
  • 18
0

In Django, you can create a unique 8 character ID field for a model by using the UUIDField with max_length=8 and default=uuid.uuid4. Here's an example of how you can define this field in your Django model.py:

import uuid
from django.db import models
from django.contrib.auth.models import User

class Transfer(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, max_length=8)
    # other fields...

The editable=False attribute prevents the field from being edited, ensuring that the value remains unique. Finally, max_length=8 ensures that the UUID is truncated to 8 characters.

Note that using UUIDs as primary keys can have some drawbacks, such as increased storage size and slower queries compared to integer primary keys. Consider your use case carefully before deciding to use UUIDs as primary keys.

-1

In order for the ID to be truly unique you have to keep track of previously generated unique IDs, This can be simply done with a simple sqlite DB.

In order to generate a simple unique id use the following line:

import random
import string
u_id = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(8))

More on strings can be found in the docs

Fanchi
  • 757
  • 8
  • 23
-1

I suggest to make a token generator class like this:

import string, random
class RandomTokenGenerator(object):
    def __init__(self, chars=None, random_generator=None):
        self.chars = chars or string.ascii_uppercase + string.ascii_lowercase + string.digits
        self.random_generator = random_generator or random.SystemRandom()

    def make_token(self, n=20):
        return ''.join(self.random_generator.choice(self.chars) for _ in range(n))

token_generator = RandomTokenGenerator()

Then in your model should be like:

from django.db import models
from django.contrib.auth.models import User
from .token_utils import token_generator
    class Transfer(models.Model):
        id = models.AutoField(primary_key=True)
        user = models.ForeignKey(User)
        timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
        token = models.CharField(_('UUID'), max_length=8, null=False)
       def save(self, *args, **kwargs):
           ## This to check if it creates a new or updates an old instance
           if self.pk is None:
              self.token = token_generator.make_token(8)
           super(Transfer, self).save(*args, **kwargs)
Ahmed Hosny
  • 1,162
  • 10
  • 21
-1

You could use the DB id and convert that to a sting using someting like this:

def int_to_key(num):
    if num == 0:
        return ""

    return "{0}{1}".format(
        int_to_key(num // 52), 
        '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'[num % 52]
    )

If you can adjust the code to use less or more characters as you need.