简体   繁体   English

如何在 Django 管理面板中批量生成唯一的优惠券代码

[英]How to Generate a unique Coupon Code In the Django Admin panel for bulk

I have used this code in models.py I'm getting the error of Gift is not defined and models are not showing in the Django admin panel# from django.db import models import secrets from django.db.models.signals import post_save我在models.py中使用了这个代码我得到了Gift未定义的错误,模型没有显示在Django管理面板中# from django.db import models import secrets from django.db.models.signals import post_save

class UniqueCodes(models.Model): """ Class to create human friendly gift/coupon codes. """ class UniqueCodes(models.Model): """ 类创建人类友好的礼物/优惠券代码。"""

# Model field for our unique code
code = models.CharField(max_length=8, blank=True, null=True, unique=True)

@classmethod
def post_create(cls, sender, instance, created, *args, **kwargs):
    """
    Connected to the post_save signal of the UniqueCodes model. This is used to set the
    code once we have created the DB instance and have access to the primary key (ID Field)
    """
    # If new database record
    if created:
        # We have the primary key (ID Field) now so let's grab it
        id_string = str(instance.id)
        # Define our random string alphabet (notice I've omitted I,O,etc. as they can be confused for other characters)
        upper_alpha = "ABCDEFGHJKLMNPQRSTVWXYZ"
        # Create an 8 char random string from our alphabet
        random_str = "".join(secrets.choice(upper_alpha) for i in range(8))
        # Append the ID to the end of the random string
        instance.code = (random_str + id_string)[-8:]
        # Save the class instance
        instance.save()

def __str__(self):
    return "%s" % (self.code,)

post_save.connect(Gift.post_create, sender=UniqueCodes) post_save.connect(Gift.post_create, sender=UniqueCodes)

我尝试将 Gift 更改为 UniqueCodes 并且它有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM