5

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

light_ray
  • 642
  • 2
  • 11
  • 31

3 Answers3

6

Maybe like this:

views.py

context = {'page_data' : json.dumps({"title": "Articles"})}

article.html

<body data="{{ page_data }}">

in vue instance

beforeMount(){
  this.page = JSON.parse(document.getElementsByTagName('body')[0].getAttribute('data') || '{}');
}
ivan wang
  • 415
  • 1
  • 5
  • 10
3

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

Community
  • 1
  • 1
2ps
  • 15,099
  • 2
  • 27
  • 47
2

You can add html to your vue-components and serve json via restful-api, using e.g. Django Rest Framework. For making the API calls you would add vue-router to vue: https://github.com/vuejs/vue-router

musicformellons
  • 12,283
  • 4
  • 51
  • 86