I am using Vue.js for the first time. I need to serialize the objects of django
views.py
def articles(request):
model = News.objects.all() # getting News objects list
modelSerialize = serializers.serialize('json', News.objects.all())
random_generator = random.randint(1,News.objects.count())
context = {'models':modelSerialize,
'title' : 'Articles' ,
'num_of_objects' : News.objects.count() ,
'random_order' : random.randint(1,random_generator) ,
'random_object' : News.objects.get(id = random_generator ) ,
'first4rec' : model[0:4],
'next4rec' : model[4:],
}
return render(request, 'articles.html',context)
I have tried to display serialized json data in html its working fine there,
Now , how to intialize json data in vue instance and to access in html using v-repeat attribute.
https://jsfiddle.net/kn9181/1yy84912/
Please can any one help???
Response Object After submitting the request, look to the right-hand portion of the Request window. You should notice the JSON response object. If it does not appear, make sure you have selected the JSON tab (highlighted in yellow below). And you're done!
Fetching Data from API js import { useEffect } from "react"; import "./App. css"; function App() { useEffect(() => { fetch(`https://dummyjson.com/products`) . then((response) => response. json()) .
A simple example.
views.py
def articles(request):
context {
'articles' : ['a1','a2','a3']
}
return render(request, 'articles.html', context)
articles.html
{% verbatim %}
<div id="app">
<ul>
<li v-for="a in articles">{{ a }}</li>
</ul>
</div>
{% endverbatim %}
<script>
new Vue({
el : "#app",
data : function(){
return {
articles : {{ articles | safe }}
}
}
})
</script>
Things to watch out for :
verbatim
tag to stop Django from rendering the contents of this block tag since Vue uses the same interpolating symbols.safe
filter to prevent Django from escaping the contents.Generally speaking, prefer passing data to Vue via Ajax
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