1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

DjangoでJavaScriptに深い構造のデータを簡単に渡す

Posted at

DjangoからデータをウェブページのJavaScriptに渡し、JSを使用して処理したい場合があります。
たとえば、Vue.jsを使用してデータをwebページに表示させます。

views.py
import json
from django.shortcuts import render


def home(request):
    books_py = [
        {
            'code': '00009',
            'name': 'はじめてのC',
            'publisher': '技術評論社',
            'price': 2178,
            'count': 1
        },
        {
            'code': '01002',
            'name': 'やさしいC++',
            'publisher': 'SOFTBANK',
            'price': 2500,
            'count': 1
        },
        {
            'code': '20006',
            'name': '実践SQL',
            'publisher': 'SOFTBANK',
            'price': 2800,
            'count': 1
        }
    ]

    return render(request, 'home.html', {'books': json.dumps(books_py)})

home.html
......

<script>

    var books = {{ books|safe }};
    console.log(books);

</script>

......

実行結果:
django02.png

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?