How to generate random numbers in django

感情迁移 提交于 2020-05-10 04:25:45

问题


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


EDIT

The random numbers must be unique.


回答1:


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




回答2:


It is more a python thing than a django thing.

You can find all the information about Random class here

Good luck!



来源:https://stackoverflow.com/questions/6353558/how-to-generate-random-numbers-in-django

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!