问题描述
我想在空白字段中生成自动随机数,同时将其保存在Django中。
I want to generate automatic random numbers in a blank field while saving it in django.
编辑
随机数必须是唯一的。
推荐答案
编辑:更改了解决方案以使随机数唯一并使用Django的make_random_password
Changed solution to make random number unique and to use Django's make_random_password
功能。请注意,以下内容假设您将随机数存储在模型UserProfile的
function. Note the below assumes you are storing the random number in a field called
temp_password字段中。
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
allowed_chars的默认值是一串字母和数字减去一些易于引起混淆的字母和数字
default value for allowed_chars is a string of letters and numbers minus a few that tend to cause
在用户(1、1等)中
有关Django make_random_password函数的更多信息:
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
在< = n< = b
in the example above a <= n <= b
随机类中还有更多类型的随机数:
Many more types of random numbers in the random class:http://docs.python.org/library/random.html
这篇关于如何在Django中生成随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!