3👍
I recommend using the Django REST Framework to connect Django to your React front-end. The usage pattern for DRF is:
- Define serializers for your models. These define what fields are included in the JSONified objects you will send to the front-end. In your case you might specify the fields ‘categories’ and ‘content.’
- Create an API endpoint. This is the URL you will issue requests to from React to access objects/models.
- From React, issue a GET request to retrieve a (possibly filtered) set of objects. You can also set up other endpoints to modify or create objects when receiving POST requests from your React front-end.
In the success function of your GET request, you will receive an Array of Objects with the fields you set in your serializer. In your example case, you would receive an Array of length 1 containing an object with fields ‘categories’ and ‘content.’ So xhr[0].content
would have the value "At least one note "
.
In your code, the call to json.dumps
within the JsonResponse function is redundant. Check out the docs for an example of serializing a list using JsonResponse. If you are serializing the object manually (which I don’t recommend), I’d use a dictionary rather than a list — something like {'categories': <value>, 'content' : <value>}
. DRF will serialize objects for you like this, so the fields are easier to access and interpret on the front-end.