How to generate random numbers in django

后端 未结 3 1839
Happy的楠姐
Happy的楠姐 2021-02-05 23:38

I want to generate automatic random numbers in a blank field while saving it in django.


EDIT

The random numbers must be unique.

3条回答
  •  一向
    一向 (楼主)
    2021-02-05 23:56

    EDIT: Changed solution to make random number unique and to use Django's make_random_password

    function. Note the below assumes you are storing the random number in a field called

    temp_password in a model UserProfile that is an extension of the User model.

    random_number = User.objects.make_random_password(length=10, allowed_chars='123456789')
    
    while User.objects.filter(userprofile__temp_password=random_number):
        random_number = User.objects.make_random_password(length=10, allowed_chars='123456789')
    

    Also note that you can store the random code as a combination of letters and numbers as well. The

    default value for allowed_chars is a string of letters and numbers minus a few that tend to cause

    confusion among users (1, l, etc.)

    More about Django's make_random_password function: https://docs.djangoproject.com/en/dev/topics/auth/#manager-functions

    OLD:

    import random
    
    n = random.randint(a,b) # returns a random integer
    

    in the example above a <= n <= b

    Many more types of random numbers in the random class: http://docs.python.org/library/random.html

提交回复
热议问题