Python 3 Django (7) Django has many ways to transfer data from the background to the front.

Keywords: JSON Django Javascript

Django has many ways to transfer data from the background to the front.

Basic form:

from django.shortcuts import render

def main_page(request):
    return render(request, 'index.html')

views to HTML usage data

views is passed to HTML to use data

  • Code in views:
from django.shortcuts import render

def main_page(request):
    data = [1,2,3,4]
    return render(request, 'index.html', {'data': data})
  • Call in html

1.html uses {}} to get data

<div>{{ data }}</div>

2. The data that can be iterated can be iterated:

{% for item in data%}
<p>{{ item }}</p>
{% endfor %}

This method can pass various data types, including list, dict and so on.
Besides {% for%}, you can also make if judgment, size comparison, etc. For specific usage, readers can search by themselves.

JavaScript call parameters

Take a simple list as an example

# -*- coding: utf-8 -*-

import json
from django.shortcuts import render

def main_page(request):
    list = ['view', 'Json', 'JS']
    return render(request, 'index.html', {
            'List': json.dumps(list),
        })

JavaScript part:

var List = {{ List|safe }};

You can also use js for and other operations
for(var i=0;i

JavaScript Ajax dynamic page refresh

The foreground uses Ajax to send the request, and the background processes the data and returns it to the foreground. The foreground does not refresh the webpage and load the data dynamically
Django Code:

def scene_update_view(request):
    if request.method == "POST":
            name = request.POST.get('name')
            status = 0
            result = "Error!"
            return HttpResponse(json.dumps({
                "status": status,
                "result": result
            }))

JS Code:

 function getSceneId(scece_name, td) {
            var post_data = {
                "name": scece_name,
            };

            $.ajax({
                url: {% url 'scene_update_url' %},
                type: "POST",
                data: post_data,
                success: function (data) {
                    data = JSON.parse(data);
                    if (data["status"] == 1) {
                        setSceneTd(data["result"], scece_name, td);
                    } else {
                        alert(data["result"]);
                    }
                }
            });
        } 
JS sends ajax request, processes the request in the background and returns status, result
 Define the callback function to process the returned data after success: using JSON.parse(data)

Posted by Paragon on Tue, 31 Mar 2020 01:16:00 -0700