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
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.
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.
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:
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.
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.
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:
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') || '{}');
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With