Jack022
Jack022

Reputation: 1257

Pass data from Django view to template

I have a very basic view that is supposed to render a page and pass some data to this page, here is how i do it:

def myview(request):

    request = mydb.objects.filter(user=request.user)

    return render(request,
                  "main/mytemplate.html",
                  context={"data":request})

When the page is loaded, the data is passed to the template, so to show that data, i'll only have to go to my html and add this:

{{data}}

But how can i do the same from a view that is not the same view that renders the page?

Let's say that this is a view that i can call with an Ajax request, so when the Ajax request is triggered, the view should send data in the same way and i want to be able to use it in the Django template language.

Here is an example:

def secondview(request):
    request = mydb.objects.filter(item='free')
    return HttpResponse(request)

This view is called from an Ajax request, it will send a response with the data, but i don't want to get the data in this format or in json format, instead i want to use it from the Django template language, just as i did with the first example. Is there any way to do it? Or can i only pass data to the template in the context?

Upvotes: 0

Views: 1487

Answers (2)

Sawant Sharma
Sawant Sharma

Reputation: 758

1) Instead of returning HttpResponse in your secondview do this

def secondview(request):
    from django.template.loader import render_to_string
    x = 1
    return render_to_string('template_name.jinja', locals())

2) If you want to display that response in your html, do this in your html,

<div id="x"> </div>

function someFunc(){
     $.ajax({
        url: "someurl",
        type: 'GET',
        success: function (response) {
            document.getElementById("x").innerHtml = response
        },
        error: function (xhr, err) {
            console.log(xhr.responseText);
        },
        cache: false,
        contentType: false,
        processData: false
});

I hope I've answered all of your questions, if not let me know.

Upvotes: 1

Nj Nafir
Nj Nafir

Reputation: 568

def myview(request):
    request = mydb.objects.filter(user=request.user)
    context = {"data":request}
    return render(request, "main/mytemplate.html", context)

Upvotes: 0

Related Questions