如何在Django中创建自动生成的会员ID

时间:2018-12-27 03:26:58

标签: django python-3.x

我想基于当前日期和用户名在配置文件表中创建用户的自动生成的会员ID。用户表与配置文件表具有OneToOneField关系。因此,当我创建用户时,必须在注册表单中放入usernamesignals.py在表中为用户创建一个配置文件行。我想在创建配置文件时拥有一个成员身份ID,即当前日期和用户名的混合。我的代码如下:

singlas.py

from django.db.models.signals import post_save, pre_save
from .models import Ext_User
from django.dispatch import receiver
from .models import Profile

@receiver(post_save, sender=Ext_User)
def create_profile(sender, instance, created, **kwargs):
   if created:
       Profile.objects.create(user=instance)

models.py

class Profile(models.Model):

    user = models.OneToOneField(Ext_User, on_delete=models.CASCADE)
    image = models.ImageField(default='default.jpg', upload_to='profile_pics', null=True, blank=False)
    membership_id = models.CharField(max_length=50, default='', null=True, blank=True)

    def __str__(self):
        return f'{self.user.username} Profile'

我已经有了一些有关将用户pre_save保存到signals.py的准则,但是不知道如何解决。

1 个答案:

答案 0 :(得分:2)

您可以尝试

@receiver(post_save, sender=Ext_User)
def create_profile(sender, instance, created, **kwargs):
   if created:
       profile = Profile()
       profile.membership_id = str(instance.username) + str(datetime.datetime.now())
       profile.user_id = instance.pk
       profile.save()

将DateTime设置为所需格式