Encountering issues with parsing a JSON object while utilizing the templateHTMLrenderer feature in Django

I'm just starting out with django and JSON, and I'm attempting to send a list of patients in JSON using the code below:

class JSONResponse(HttpResponse):
    """
    An HttpResponse that converts content into JSON format.
    """
    def __init__(self, data, **kwargs):
        content = JSONRenderer().render(data)
        kwargs['content_type'] = 'application/json'
        super(JSONResponse, self).__init__(content, **kwargs)

@api_view(('GET',))
@renderer_classes((TemplateHTMLRenderer,))
@csrf_exempt
def patient_list(request):
    """
    List all records or create a new snippet.
    """
    if request.method == 'GET':
        #data = Patient.objects.all()
        data= Patient.objects.all()
        #serializer = PatientSerializer(data, many=True)
        #return JSONResponse(serializer.data)
        return Response({'patients': data}, template_name='records.html')

In the records.html file, there is the following JavaScript code:

<script type="text/javascript">
    var data = "{{patients}}";
    var parsed = JSON.parse(data);
</script>
...
<h2> <script type="text/javascript">document.write(data);</script></h2>  This is not actually true, as I am exploring how to achieve this

However, when printing the data (as a string just to see what's available), it shows something like this:

 [<Patient: Patient object>, <Patient: Patient object>, <Patient:  Patient object>, <Patient: Patient object>, <Patient: Patient object>, <Patient: Patient object>, <Patient: Patient object>]

My understanding is that serialization is not required when using Response. I simply want to retrieve the list of patients and display their first name for example. Any guidance on accomplishing that?

Answer №1

If you're looking to take the longer route, then utilizing Django's JsonResponse class would be a suitable option: https://docs.djangoproject.com/en/1.9/ref/request-response/#jsonresponse-objects. However, if you are working with DjangoRestFramework, creating a serializer class and implementing a ViewSet might be more appropriate.

For your serializers.py:

from rest_framework import serializers

class MySerializer(serializers.ModelSerializer):

  class Meta:
    model = MyModel

In your views.py:

from rest_framework import viewsets
from .serializers import MySerializer

class MyViewSet(viewsets.ModelViewSet):

  serializer_class = MySerializer
  queryset = MyModel.objects.all()

In urls.py:

from rest_framework import routers
from .views import MyViewSet

router = routers.SimpleRouter()
router.register(r'mymodel', MyViewSet)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Determining the moment a user exits a page on Next JS

Is there a way to track when the user exits a Next JS page? I have identified 3 possible ways in which a user might leave a page: Clicking on a link Performing an action that triggers router.back, router.push, etc... Closing the tab (i.e. when beforeunloa ...

What is the method for binding context on a click event in Vue?

Can't access context function on click in Vue Example HTML with click function: <li v-on:click="itemClick($event, this)"></li> My Vue.js code snippet: var app = new Vue({ el: '#mainApp', methods: { ite ...

Issue: Troubleshooting data serialization process using getStaticProps in Next.js

I attempted to retrieve data from an API, but unfortunately encountered the following error: Server Error Error: Issue with serializing .results returned from getServerSideProps in "/". Reason: JSON serialization does not support undefin ...

What is the best way to incorporate Photoswipe into jQuery Mobile pages?

Trying to incorporate photoswipe into a jquerymobile app is proving to be challenging. The development involves using jquerymobile & Django, and the goal is to set up a gallery on one of the pages. There are three main pages in this setup: the category ind ...

Make an AJAX GET call to an ASP.NET Web API endpoint

Here is the ajax script I am using: $.ajax({ dataType: 'json', url: url, data: tuDispId, type: "GET", success: function (data) { bindData(data); $("#ale ...

Arranging HTML elements with jQuery - the existing script flips back and forth

I have created a code snippet on CodePen that showcases a feature of the website I am currently developing: http://codepen.io/barrychapman/pen/BzJGbg?editors=1010 Upon loading the page, you will notice 6 boxes. The first box is active, while the remaining ...

Transform two fixed elements into dynamic elements using JQuery

Is there a way to replace two static elements in the table <tr class="item-row"> with data from an ajax call instead of just appending to them? Currently, I am using this javascript line to append: $(".item-row:last").after('<tr class="item- ...

Is there a way to switch on and off an ngrx action?

Here is a statement that triggers a load action to the store. The relevant effect will process the request and return the response items. However, my goal is to be able to control this action with a button. When I click on start, it should initiate dispa ...

Parsing a Json object that contains a field with two distinct types, one of which is recursive

In my project, I have a TypeScript component that retrieves JSON data, and I need to parse this JSON in C# to work with the objects. However, due to the presence of: multiple type fields recursion it's becoming challenging to understand how the dese ...

Issue with response.split(",")[0] in Internet Explorer

Here is the code snippet I am struggling with: <script> $('#blah').on('click', function(){ $.ajax({ type: 'POST', url: 'ajax.php', data: {"xxx":"yyy", "zzz":"nnn ...

Error encountered: Django Rest API does not allow the method "POST" with React

I am currently working on developing a REST framework using Django and React. However, I have encountered an issue while attempting to create a new product. The error message I receive is: Method "POST" not allowed. within my product_views.py fi ...

Can someone explain how to implement an onclick event for a div element inside an iframe using jquery or javascript?

Understanding the HTML Structure <iframe src="#" scrolling="no" id="gallery-frame"> <div class="gv_filmstrip"> <div class="gv_frame"> <div class="gv_thumbnail current"> <img src="images/grandstand-padang-right/1.jpg"> </d ...

best way to return a function variable in JavaScript

Hey there, I've been working with react native and have run into a bit of an issue... const SignIn = () => { screensplash() fetch('http://api.megamouj.ir/api/v1/logincheck/', { method: 'POST', headers: { ...

Execute function periodically using Vue.js

I have a requirement to update data periodically by calling a function in my Vue.js application. I am looking to call the 'listar()' method every 30 seconds and store the response in a property of vue js. If anyone can guide me on where to locat ...

Display the feedback within the div container

I am using AJAX to call a method and I'm receiving a response successfully. However, I am struggling to display that response in a div. I want the response to be shown in a #result div element. <div id="result"></div> <input type="butt ...

What is the best way to delete rows from a table that was created using a JQuery AJAX response?

I am currently working on a coding project where: The user is required to input a location, Clicks on a button to execute a GET call in order to fetch data based on the specified location, and A table is then filled with the retrieved data. My goal is t ...

Node server optimization for images

Currently, I have a server set up for uploading images. In order to enhance the image upload process, I am looking for ways to optimize it. This is my current function for uploading files: uploadImage(file, uid, res) { var fs = require('fs') ...

Error encountered while trying to store a JSON object in local storage

When attempting to insert a JSON in localStorage, I am encountering the error Unexpected token ~ in JSON at position 3 during the parse process. Here is how I am inserting the data into localStorage: localStorage.setItem( "users", `"[\"~#iM& ...

Utilizing the builder pattern for deserializing inheritance in Java with Jackson

I have a parent class called Foo with 2 subclasses named A and B. Here is an overview of their structure: public abstract class Foo { private String fooString; public Foo(String fooString) { this.fooString = fooString; } //getter } @JsonDeser ...

While using Alamofire in Swift 4, encountered a JSON parsing error from the server during request

When trying to make a post request to the api in order to retrieve data from the response, the api provides two possible responses: { valid: true } or { valid: false } The Alamofire request I am using is structured as follows: parameters = ["k ...