0

Is there a way to validate params that are passed with the request without writing boilerplate code? Now I've got something like this:

    project_id = kwargs['project_id']

    try:
        project_obj = Project.objects.get(id=project_id)
    except Project.DoesNotExist:
        return Response(
            {'message': 'Requested project does not exist'},
            status=status.HTTP_404_NOT_FOUND
        )
    except ValueError:
        return Response(
            {'message': 'Project id must be a number'},
            status=status.HTTP_400_BAD_REQUEST
        )

I've read about Serializers' Validation but I'm not sure it's the right thing. Without handling these exceptions, Django just returns 500, it's not the behavior I actually want.

1
  • I don't know of a clever way to check to see if an objects exists in the database with, you know, checking to see if it's in the database. I suppose a cheesy way would be to get a list of the all the project_ids and see if your ID passed in is in that list. To the other error you are catching, ValueError, you can write a simple check to see if project_id is a number and if not simply send back an error of your choice instead of catching the exception. Commented May 23, 2019 at 19:42

1 Answer 1

1

You are going to wind up writing some boilerplate, but you can clean what you have up by specifying relevant field types like using an IntegerField would spare you checking the type and get_object_or_404 would spare you the try/ catch in those cases.

However, you really want to use the real right field for this job and it's going to be a Relation field, most likely PrimaryKeyRelatedField.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.