python - Django:在提交表单时生成唯一的 8 字符字母数字 ID 字符串

标签 python django forms identifier alphanumeric

有人可以帮我在我的模型中创建一个字段,在每次用户提交表单时生成一个唯一的 8 字符字母数字字符串(即 A#######)ID 吗?

我的 models.py 表单目前如下:

from django.db import models
from django.contrib.auth.models import User

    class Transfer(models.Model):
        id = models.AutoField(primary_key=True)
        user = models.ForeignKey(User)
        timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)

我查看了 python 的 UUID 功能,但与我希望生成的相比,这些标识符非常长且困惑。

如有任何帮助,我们将不胜感激!

最佳答案

像这样:

''.join(random.choice(string.ascii_uppercase) for _ in range(8))

关于python - Django:在提交表单时生成唯一的 8 字符字母数字 ID 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35127452/

相关文章:

python - 仅运行特定文件的测试

python - 致命 python 错误 :initfsencoding:unable to load the file system codec? 的原因可能是什么

python - Tanh-sinh求积数值积分法收敛到错误值

python - 如何使用 Python 检查 NIFTI 图像是否处于正确的方向/位置

python - Django,按一个字段分组,只取每组的最新/最大值并取回ORM对象

python - Django RequestFactory 添加 HTTP_X_FORWARDED_FOR

javascript - 根据其他选择框的值生成选择框的值

python - Django Rest 中的序列化器不返回关系对象

javascript - 如何将动态表单保存到数据库/编辑表单

html - 如何在html中一次提交打开两个页面?