How to pass JSON data from the Django view to the View.js instance methods

advertisements

I am new To Vue.js . How to pass JSON data from Django view to vue instance(method).

Views.py

def articles(request):
    model = News.objects.all() # getting News objects list
    random_generator = random.randint(1, News.objects.count())
    context = {
              'title' : 'Articles' ,
              'modelSerialize' :  serializers.serialize('json',News.objects.all()),
              'num_of_objects' : News.objects.count() ,
              }
    return render(request, 'articles.html',context)

VueScript.js

new Vue({

    el: '#list-Of-Articles-Displayed',
                data: {
                   count: 0
              },
        ready: function() {

          this.$http.get('http://127.0.0.1:8000/article/').then(function (response) {
              response.status;
              console.log(response);
          }, function (response) {
                  alert("error ");
              // error callback
          });

        }

        })

Template(article.html)

<div id = "list-Of-Articles-Displayed" class = "col-lg-10" v-for="news in loadArticles" >
<div class = "col-lg-11">
   <br>
   <a href = "<%news.id%>" ><%news.title%></a>
   <h5><small><%news.date%></small></h5>
   <p>
      <%news.body%>...<span style = "color : purple" > <a href = "<%news.id%>"> Call to Action</a>
      <br><br></span>
   </p>
</div>

I am trying to access JSON data in VueScript.js , instead of JSON data I am getting complete HTML structure.

Can any one help me.? Thanks


Maybe you should use a JsonResponse instead:

from django.http import JsonResponse

def articles(request):
    model = News.objects.all() # getting News objects list
    random_generator = random.randint(1, News.objects.count())
    context = {
              'title' : 'Articles' ,
              'modelSerialize' :  serializers.serialize('json',News.objects.all()),
              'num_of_objects' : News.objects.count() ,
              }
    return JsonResponse(context)

The problem that you are getting is that render returns a Response with a content-type of text/html and what you need for the ajax call is a Response with a content-type of application/json. The JsonResponse is a fast way to make sure you have the right content-type for the response. You can read more about JsonResponse here or read this StackOverflow answer