3

I've been looking for info about this for hours without any result. I am rendering a page using React, and I would like it to display a list of Django models. I am trying to use ajax to fetch the list of models but without any success.

I am not sure I understand the concept behind JSon, because when I use the following code in my view:

data = list(my_query_set.values_list('categories', 'content'))
return JsonResponse(json.dumps(data, cls=DjangoJSONEncoder), safe=False)

It seems to only return a string that I cannot map (React says that map is not a function when I call it on the returned object). I thought map was meant to go through a JSon object and that json.dumps was suppose to create one...

Returned JSon "object" (which I believe to just be a string): For the time being I have only one test model with no category and the content "At least one note "

[[null, "At least one note "]]

React code:

$.ajax({
        type:"POST",
        url: "",
        data: data,
        success: function (xhr, ajaxOptions, thrownError) {

            var mapped = xhr.map(function(note){
                return(
                    <p>
                        {note.categories}
                        {note.content}
                    </p>
                )
            })

            _this.setState({notes: mapped})
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert("failed");
        }
    });

Can someone please point me to the best way to send Models from Django to React, so I can use the data from this model in my front end?

1 Answer 1

3

I recommend using the Django REST Framework to connect Django to your React front-end. The usage pattern for DRF is:

  1. 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.'
  2. Create an API endpoint. This is the URL you will issue requests to from React to access objects/models.
  3. 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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for your response. Do you have an example of creating an API end point to just get form data and show a blank form to the user to fill? I have been asking for it here: stackoverflow.com/questions/42297614/django-forms-with-reactjs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.