Home > Enterprise >  Autofill Models in Django
Autofill Models in Django

Time:08-02

What I'm trying to implement is an invite system while I develop my website, but I'm new to how Django works.

For now, I want to be able to create a random string in the admin panel, have those added to the database, and then be required for a user to register. Eventually I want to create a user group system on the front end website where I can generate the strings there versus the admin panel, and then be able to send them out that way, but I'll get to that later.

I have the Model showing successfully in the admin panel, but I don't know how to make a text field that's automatically filled out anytime I create a new one and have the string be random each time.

class randomString(models.Model):
    name = models.CharField(max_length=200)
    random = models.ManyToManyField(get_random_string(length=6))

This is my current code which is throwing out an error, but I assumed that it would, I did it this way just to check and see if it was this simple. I have found out that it's not.

CodePudding user response:

You can simply use an UUID:

from uuid import uuid4

class randomString(models.Model):
   name = models.CharField(max_length=200)
   random = models.UUIDField(unique=True, default=uuid4)

If the UUID is too long, you can generate a shorter string:

def generate_random():
    from django.utils.crypto import get_random_string
    return get_random_string(length=11)


class randomString(models.Model):
   name = models.CharField(max_length=200)
   random = models.CharField(default=generate_random, max_length=11, unique=True)
  • Related