1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

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

Discussão em 'Python' iniciado por Stack, Setembro 23, 2024.

  1. Stack

    Stack Membro Participativo

    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?

    Continue reading...

Compartilhe esta Página