pythondjangomodel-view-controllerdjango-rest-frameworksms-verification

How to run our function in Django restframwork


I want to run my function to do something in a request to url of serializer

my serializer :

class usersSerializer(ModelSerializer):
    class Meta:
        model=users
        fields="__all__"    

my view for serializer:

class usersCreate(generics.CreateAPIView):
    queryset=users.objects.all()
    serializer_class=usersSerializer

my function:

def f():
    now=datetime.now()
    now10=now + timedelta(minutes = 10)
    quer=users.objects.last()
    rcode=randint(1000,9999)
    a=SMS(users_id=quer,code=rcode,expireTime=now10)
    a.save()

SMS is another table users_id ====> foreigne key to id in users table

I want to when I send request to user create url changed two table : users SMS

models:

class users(models.Model):
    number=models.CharField(verbose_name="userNumber",max_length=11)
    name=models.CharField(verbose_name="name",max_length=40)
    createTime=models.DateTimeField( auto_now_add=True,auto_now=False)
    status=models.BooleanField(default=False)

class SMS(models.Model):
    users_id=models.ForeignKey(users,on_delete=models.CASCADE,default=0)
    code=models.PositiveSmallIntegerField(verbose_name="randomCode")
    expireTime=models.DateTimeField()
    status=models.BooleanField(default=False)

Solution

  • On models.py you can use signals. Which is safer then assuming the LAST will return the current user for an SMS message.

    from django.db.models.signals import post_save,pre_save
    
    @receiver(post_save, sender=users)
    def post_save_users(sender, instance, created, **kwargs):
        if created:
            now=datetime.now()
            now10=now + timedelta(minutes = 10)
            quer=users.objects.last()
            rcode=randint(1000,9999)
            sms = SMS(user_id=instance,code=rcode,expireTime=now10)
            sms.save()
        instance.save()