Download the json data for the first request and display it on the main page

I am using Vue.js for the first time. I need to serialize django objects

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 tried to display serialized json data in html, there it works fine,

Now, how to install json data in a vue instance and access html using the v-repeat attribute.

https://jsfiddle.net/kn9181/1yy84912/

Please can someone help ???

+6
source share
1 answer

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> 

Beware:

  • The verbatim tag to stop Django from displaying the contents of this block tag, as Vue uses the same interpolating characters.
  • safe filter to prevent Django content from spreading.
  • If you are going through a dictionary, consider including it in JSON first.

Generally speaking, prefer to pass data to Vue through Ajax

+5
source

All Articles