Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load json data for the first time request and to display the same in Home Page

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???

like image 432
light_ray Avatar asked Mar 20 '16 13:03

light_ray


People also ask

How do I view a JSON request?

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!

How display JSON data from API in react?

Fetching Data from API js import { useEffect } from "react"; import "./App. css"; function App() { useEffect(() => { fetch(`https://dummyjson.com/products`) . then((response) => response. json()) .


1 Answers

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 :

  • The verbatim tag to stop Django from rendering the contents of this block tag since Vue uses the same interpolating symbols.
  • The safe filter to prevent Django from escaping the contents.
  • If you are passing a dictionary, consider turning it into JSON first

Generally speaking, prefer passing data to Vue via Ajax

like image 194
zxzak Avatar answered Sep 30 '22 15:09

zxzak