Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Autofill Models in Django

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading