REST framework: enforcing mandatory values in serializer

Hello,

I’m using the Django REST framework.

I have a GET endpoint in a view where I want to ensure that parameter values are supplied when a request is made.

To do this, I pass the values supplied in the request through to a serializer, which looks like this:

from rest_framework import serializers

class MySerializer(serializers.Serializer):
    a = serializers.CharField(required=True, allow_null=False, allow_blank=False)
    b = serializers.CharField(required=True, allow_null=False, allow_blank=False)

In the get() method in the view, I do this:

request = MySerializer(data={"a": kwargs["a"], "b": kwargs["b"]})

if request.is_valid():
    ... do stuff...

If I run a unit test to send a request where the supplied value for b is None, like this:

params = {"a": "value", "b": None}

url = reverse("my-view-name", kwargs=params)
client.get(url, **DEFAULTS)

… the serializer considers the request to be valid. I would expect it not be valid as the value of b is None.

If I print the value of str(request.data), I see this:
{'a': 'value', b': 'None'}

This seems like a simple issue so I must be doing something obviously incorrect. Could anyone assist, please?

Thank you in advance.

If it’s always the same number and type of variables, then the easiest way to do this is make them (the parameters) part of the url.

Now, from what you’ve posted:

'None' (A string of the word “None”) is not the same as the Python value None. For what you’re getting in request.data, you would need to check b != 'None'.