0

I am trying to add custom field error messages for SlugRelated field as follows:

class Test(serializers.ModelSerializers):
    team = serializers.SlugRelatedField(queryset=Team.objects.all(), slug_field='name',
                                        error_messages={"does_not_exist": "Team not found"})

Works as expected. My query is how do I pass the team name dynamically in the error message. I tried the following but it did not work:

class Test(serializers.ModelSerializers):
    team = serializers.SlugRelatedField(queryset=Team.objects.all(), slug_field='name',
                                        error_messages={"does_not_exist": f"Team {team} not found"})

1 Answer 1

1

The default error message for does_not_exist take slug_name & value as the keyword argument to format the error string.

Solution is to replace team with value.

Solution:

class Test(serializers.ModelSerializers):
    team = serializers.SlugRelatedField(
        queryset=Team.objects.all(),
        slug_field='name',
        error_messages={"does_not_exist": "Team {value} not found"}
    )

Ref: relations:SlugRelatedField Source Code

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

1 Comment

Right. Forgot to convert it back to regular string from f-string. Updating the answer.

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.