pythondjangodjango-modelsdjango-admin

How to set a random integer as the default value for a Django CharField?


My models.py looks like this:

import random
random_string = str(random.randint(10000, 99999))

class Content(models.Model):
    ......
    unique_url = models.CharField(default = random_string)

When I add a content in admin, an integer in the range is generated and put into the charfield as its default value. From there, I can simple add more words to the charfield. However, the problem with my current set-up is that the integer remains the same every time I add a new article. I want to generate and insert the random integer as I am using the unique_url field to basically find each of my specific objects, and I am expecting a lot of content, so adding the random number will generally ensure that each content has a one of a kind unique_url.

Therefore, I am looking for a system which generates a random integer everytime a new content is added using the admin panel, and puts it as the default of one the fields. Is such a thing even possible in Django?


Solution

  • This way you generate a random number once. You need to define a function such as:

    def random_string():
        return str(random.randint(10000, 99999))
    

    And then define your model as you already have, without () in order to pass a reference to the function itself rather a value returned by the function:

    class Content(models.Model):
        ......
        unique_url = models.CharField(default = random_string)