Django signal is not working on post_save() of CourseOverview create then create an entry in CustomCourseOverview table also

signals.py @receiver(post_save, sender=CourseOverview) def add_custom(sender, instance,created,**kwargs): course, _=CustomCourseOverview.objects.update_or_create(course=instance.id)

models.py

class CustomCourseOverview(TimeStampedModel): course = models.OneToOneField( CourseOverview, db_constraint=False, db_index=True, on_delete=models.CASCADE, )

apps.py def ready(self):

  also add signal valid path  

It is not working because there may be a case where the data you are entering to create a model object does not validate in any form or does not fit in the model defined requirement , like max_length increased or any way.

Both the signals are fired while creation of model object , while creation pre_save is fired and while saving it post_save is fired, but due to some cause if the instance is not saved you cannot get the instance in the code snippet in signals if it is not created, if not created you cannot have instance.id which will give a definite error .

here in line 3 there is chance of error :

@receiver(post_save, sender=CourseOverview)
def add_custom(sender, instance,created,**kwargs):
    course, _=CustomCourseOverview.objects.update_or_create(course=instance.id)

so add an if statement stating that do the creation stuff , created parameter gives bool value telling the object is created or not . ( true or false ) so you will get the instance .

@receiver(post_save, sender=CourseOverview)
def add_custom(sender, instance,created,**kwargs):
    if created : 
        course, _=CustomCourseOverview.objects.update_or_create(course=instance.id)
        course.save()

If you want to update the thing . You cannot do it because , there may be case where your CourseOverview is linked with another CustomCourseOverview model , and hence its not possible .

Try using simple appraoch . When its created , fire a post_save signal to create a new CustomCourseOverview object , and for updating the thing , use forms or some other way . That will do the work.

Back to Top