0

I'm trying to write an APIView using the Django REST framework. In the POST method I want to check if the request data contains anything, because I often get KeyError.

I can achieve it using the following code:

        if request.data is not None and request.data != {}:
            username = request.data["username"]

Is there a better way to write the above code? Especially request.data != {}

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
xahiru
  • 41
  • 1
  • 6
  • You're basically asking how to validate an empty dictionary. Repeated question answer can be found here. https://stackoverflow.com/questions/23177439/python-checking-if-a-dictionary-is-empty-doesnt-seem-to-work – Cl0ud-l3ss Nov 10 '21 at 11:02
  • Empty dictionaries evaluate to False. So you could simply use `if not` to validate – Cl0ud-l3ss Nov 10 '21 at 11:02

2 Answers2

1

Since empty dictionaries evaluate to False, you could simply use an if not operator to validate the data.

As easier approach to your code would be to

if not request.data:
   username = request.data["username"]

You can learn more here


Alternatively, you could use a serializer to validate the fields. Here is an example on how you can implement this:

class CommentSerializer(serializers.Serializer):
    email = serializers.EmailField()
    content = serializers.CharField(max_length=200)
    created = serializers.DateTimeField()

^Assuming that those are your fields. You can change them to your model fields.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
jahantaila
  • 840
  • 5
  • 26
0

The first suggestion in Django REST framework is to use a serializer which will validate the fields. Take a look at Serializers.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131