I have a model with a JSONField in Django. If I issue POST through the browser using Django Rest UI, the data gets entered into the model with no issues. However,when I use Python’s requests.post in my application, everything except the JSONField data stores in the model.
Here is my model
from django.db import models from django.contrib.postgres.fields import JSONField class Scans(models.Model): Name = models.CharField(max_length=20) Server = models.CharField(max_length=20) Results = JSONField(default=dict) Report_Url = models.URLField(max_length=30)`
Here is my Serializer
from rest_framework import serializers from .models import Scans class ScansSerializer(serializers.ModelSerializer): class Meta: model = Scans fields = '__all__'
Here is my view
class ScansData(APIView): def get(self, request): scans = Scans.objects.all() serializer = ScansSerializer(scans, many=True) return Response(serializer.data, status=status.HTTP_200_OK) def post(self, request): serializer = ScansSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request): scans = Scans.objects.all() scans.delete() return Response(status=status.HTTP_204_NO_CONTENT)
Here is my request
data = { "Name": "dodo", "Server": "ubuntu", "Report_Url": "https://127.0.0.1:8000/about/" } jsonval = { "Results": { "Severity_High": 8, "Severity_Medium": 7, "Severity_Low": 5 } } requests.post('http://127.0.0.1:8000/scans/', data=data, json=jsonval)
URL
urlpatterns = [ path('scans/', ScansData.as_view()), ]
What I see after using requests.post
{ "id": 10, "Name": "dodo", "Server": "ubuntu", "Results": {}, "Report_Url": "https://127.0.0.1:8000/about/" }
Advertisement
Answer
try data in this format .
data = { "Name": "dodo", "Server": "ubuntu", "Report_Url": "https://127.0.0.1:8000/about/", "Results": json.dumps({ "Severity_High": 8, "Severity_Medium": 7, "Severity_Low": 5 }) }
and remove jsonvalue
requests.post('http://127.0.0.1:8000/scans/', data=data)