Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Pass JSON data from Django view to Vue.js instance methods

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

like image 240
light_ray Avatar asked Mar 28 '16 03:03

light_ray


People also ask

How do I get data from JSON file in Vue?

To get data from a local JSON file, we need to import the file into the component where we want to process the data. We do the import just like we would with a component, except the component name is replaced with whatever we want to call the data set.

Is Vue compatible with Django?

We have the Django REST API and the Vue client app here. These apps run on different URLs, thus, they have different origins. URLs with similar protocols, domains, and ports are considered to be of the same origin. In this case, the REST API is running on port 8000, so we can't use this port to run the Vue client app.

How to use Vue JS in Django?

Use Vue.JS in Django templates # The other way to use Vue in Django is to simply import the Vue.JS library and then start coding. Here is how you can do that. Import the Vue.JS library. Preferably at the bottom of your template (right before the </body> tag), import the library with this line of code:

How do I return JSON from an API in Django?

Returning a JSON Response from an API. Django provides a built-in class JsonResponse that makes returning JSON easy. By default, the JsonResponse class sets a Content-Type header of application/json. Let’s make an API call to the CocktailDB API that will return a list of cocktails and their ingredients to pass on as a JsonResponse to our frontend.

How to convert a queryset to JSON in Django?

Getting your model objects as JSON is convenient, but the way Django converts a QuerySet to JSON is probably not what you would first expect. To return a QuerySet of model objects, we first have to convert the QuerySet to JSON. The process of converting one data type to another is called serialization.

Is it possible to use Django templates with Vue templates?

We will have to change the ones from the Django template language or Vue, otherwise, the Django template language will always render them first and Vue won't be able to do anything with them anymore. It's best to change the Vue ones by adding delimiters:


Video Answer


2 Answers

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') || '{}');
}
like image 140
ivan wang Avatar answered Sep 28 '22 08:09

ivan wang


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

like image 28
2ps Avatar answered Sep 28 '22 06:09

2ps