Search code examples
pythondjangodjango-rest-frameworksignals

How to render signals.py error message to the django-rest API?


I am trying to render the error message from Django signals.py file to django-restframework views.py. I created the views.py file like this,

class HazardIndexViewSet(viewsets.ModelViewSet):
    queryset = HazardIndex.objects.all()
    serializer_class = HazardIndexSerializer
    permission_classes = [permissions.IsAuthenticated]

My signals.py file looks like,

@receiver(post_save, sender=HazardIndex)
def publish_to_geoserver(instance, created, *args, **kwrgs):
    try:
        geo.create_coveragestore(instance.name, instance.workspace_name, path=instance.file)
    except Exception as e:
        instance.delete()
        print("Something is wrong while creating coveragestore")     

I want this print statement(print("Something is wrong while creating coveragestore")) to display the error message in API. And another things is, I want to create the instance only if the publish_to_geosever function runs successfully. Otherwise it should through error. Any help?


Solution

  • You could raise rest_franework exception so that it would appear in the API. Here I am using ValidationError as it gives 400 status code in the response and in the body it will show your printing message:

    from rest_framework.exceptions import ValidationError
    
    @receiver(post_save, sender=HazardIndex)
    def publish_to_geoserver(instance, created, *args, **kwrgs):
        try:
            geo.create_coveragestore(instance.name, instance.workspace_name, path=instance.file)
        except Exception as e:
            instance.delete()
            raise ValidationError("Something is wrong while creating coveragestore")   
    
    

    Regarding your second question about creating on success, I guess it is fine to leave it as it is, because it tries to create your geo object and if it can not, then it will raise an error in the API.