lese
lese

Reputation: 549

Django - How to render html and return a json at the same time

I have a view which populate a json object, and then, at the end of the same view I would render an html page, but also return the final json.

probably this is not relevant but the json would be for example something like this:

{
    "embedToken": "dasfgjasdàgjasdàgasdàgèe-AveryLongToken",
    "embedUrl": "https://app.powerbi.com/let's_go_to_the_lake",
    "reportId": "e615-sfash-9746"
}

the line I'm not able to fix (tried all day with all alternatives methods) is the following:

return render(request, "home.html", jsn)

my url.py is simple as follow:

urlpatterns = [
    path('', HomePageView, name='home'),
]

I currently get the following error:

context must be a dict rather than str.

But I encountered all different kinds of errors on the way without succeeding to reach the desired result(rendering the html and returning the json at the same time). So my doubt is that I'm taking the wrong approach at the basics, should I change road?

I would like to try to convert the json into a dictionary, and then maybe convert it back in a json in JavaScript

I have also tried to split my requests, by rendering the html as a Django view, and performing the function call from JavaScript ajax request as follow:

function handler1(){
    // there are many other methods like $.get $.getJSON
    $.ajax({
       type: 'GET',
       dataType: 'json',
       url: "http://piedpiper.com/api/callers"
    }).then(function(result) {
        // do something with the result

    });
}

But I ended up by understanding that in this way I must create the URL api/callers which will be available/reachable to everybody, which I cannot do, because of the user session. only the logged in user must see the json data

Upvotes: 3

Views: 2364

Answers (1)

Iakovos Belonias
Iakovos Belonias

Reputation: 1373

You need to add the proper arguments on render. Here is the docs for render function in Django

Here is a sample code of a view

def post_detail(request, slug=None):
    instance = get_object_or_404(Post, slug=slug)
    share_string = quote_plus(instance.content)
    context = {
        "title": instance.title,
        "instance": instance,
        "share_string": share_string,
    }
    return render(request, "post_detail.html", context)

Upvotes: 2

Related Questions