2

I'm currently trying to make a post request with only data field in models.py:

class Filter(models.Model):
    class Meta:
        verbose_name_plural = "Filter"
        verbose_name = "Filter"
        db_table= "listing_filter"

    data = JSONField(default={})

    user = models.ForeignKey('backend.user', on_delete=models.CASCADE)

I have the following Serializer , i use JSONField following the drf document docs:

class FilterSerializer(serializers.ModelSerializer):
    data = serializers.JSONField(required=True)
    user = serializers.CharField(required=False)

    class Meta:
        model = Filter
        fields = ('__all__')

and use it in the APIView:

class FilterView(APIView):
   def post(self, request):
        login_user = request.user
        received_json_data=json.loads(request.body)
        valid_ser = FilterSerializer(data=received_json_data)
        if valid_ser.is_valid():
            post_data = received_json_data["data"]
            filter = Filter.objects.create(data=post_data, user=login_user)
            filter.save()

            return JsonResponse({'code':'200','data': filter.id}, status=200)
        else:
            return JsonResponse({'code':'400','errors':valid_ser.errors}, status=400)

When i send the following data in body it worked and saved the object:

{
    "data": {
        "http://example.org/about": {
            "http://purl.org/dc/terms/title": [
                {
                    "type": "literal",
                    "value": "Anna's Homepage"
                }
            ]
        }
    }
}

But when i send data as a string(which is not a json object) it still save, how do i prevent this ?

{
    "data" : "abc"
}
Marat Mkhitaryan
  • 844
  • 2
  • 11
  • 25
Linh Nguyen
  • 3,452
  • 4
  • 23
  • 67
  • 2
    What you need actually is `DictField` https://www.django-rest-framework.org/api-guide/fields/#dictfield for `data` field validation. – Akshay Pratap Singh Sep 10 '19 at 04:16
  • You are wrong, A string is also a valid JSON value but not valid JSON object. See more https://stackoverflow.com/questions/7487869/is-this-simple-string-considered-valid-json – Akshay Pratap Singh Sep 10 '19 at 04:18
  • i see, but is there an option to modify serialization to only accept json object? – Linh Nguyen Sep 10 '19 at 04:22
  • No there is not very specific types of field provided by drf serializers for validating JSON dict or array, but you either create it or you can use ``DictField` if you are planning to only accept data as `{}` dict type value. – Akshay Pratap Singh Sep 10 '19 at 04:28
  • but what if the data is in {} but it only has key and no value or the key are not in a double quote or single quote, it will still be accept – Linh Nguyen Sep 10 '19 at 04:30
  • You can give a try to `DictField`, i think it do such checks. otherwise go with custom implementation. – Akshay Pratap Singh Sep 10 '19 at 04:31
  • i used DictField and it help,i guess it's a way. If you make a post i will accept it as an answer :)) – Linh Nguyen Sep 10 '19 at 05:03

0 Answers0