demand
On a daily basis, django returns most of the requests it receives from the front end in JSON format, as well as templates that return views. Returning a view in a template is handy, but when it comes to things like static/static separation and Ajax requests, Django can only return data in JSON format. This brings up the problem of putting the data django queries from the database model classes back to the front end in JSON format. And then what if the front end gets the data that comes back from the read?
The environment that
- The front-end uses jquery to send Ajax requests
- Python 3.7.2
- Django 2.1.7
example
This example starts by writing a simple page to send an Ajax request, and then illustrates how the back end can return multiple rows of data if the query object is returned.
The front-end code
First write a simple front page test_ajax.html as follows:
<! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="/ static/js/jquery - 3.0.0. Min. Js." "></script>
<script>
$(function() {$('#search_server').click(functionVar server_name = $('#server_name').val();
console.log('server_name = '+ server_name); // Send an Ajax post request $. Ajax ({url:"/assetinfo/test_ajax".type: 'POST',
data: {
"tag": "search_project"."server_name": server_name,
},
dataType: "json",
async: false// Call the function success:function(data) { console.log(data); }, // call error when request error:function () {
alert("Failed to query project data send");
}
})
})
})
</script>
</head>
<body>
<input type="text" id="server_name">
<button id="search_server"</button> </body> </ HTML >Copy the code
The implementation is as simple as getting the contents of the input box and clicking the submit button to send an Ajax POST request.
The background directly queries server information and returns multiple JSON data
The code to implement the class view is as follows:
from django.core import serializers
from django.http import HttpResponse
from assetinfo.models import ServerInfo
# ex: /assetinfo/test_ajax
class TestAjax(View):
def get(self,request):
"""Display HTML page"""
return render(request,'assetinfo/test_ajax.html')
def post(self,request):
"""Receive POST requests to handle Ajax"""
servers = ServerInfo.objects.all() # query server information
json_data = serializers.serialize('json', servers) Json serialize the query results
return HttpResponse(json_data, content_type="application/json") # return JSON data
Copy the code
In the background code, I did not get the parameters of the POST request, and then the parameter query operation, so I only show how to return JSON format data.
Request. Post. Get (‘ parameter name ‘).
The browser test functions are as follows:
You can see the resulting data returned from the back end from the browser console.
But it’s not good to go straight back to the front end with no task constraints, so let’s add a format constraint to the interaction with the front end.
Back – end constraints return data formats
{"resCode": '0'."message": 'success'."data": []}
Copy the code
According to this constraint format, the result of the query should be placed in an array of data. Let’s change the back-end view code.
The back end returns JSON data in a constraint format
from django.core import serializers
from django.http.response import JsonResponse
from assetinfo.models import ServerInfo
# ex: /assetinfo/test_ajax
class TestAjax(View):
def get(self,request):
"""Display HTML page"""
return render(request,'assetinfo/test_ajax.html')
def post(self,request):
"""Receive POST requests to handle Ajax"""
# and the front-end convention return format
result = {"resCode": '0'."message": 'success'."data": []}
# query server information
servers = ServerInfo.objects.all()
Serialize to Python objects
result["data"] = serializers.serialize('python', servers)
return JsonResponse(result)
Copy the code
The browser tests are as follows:
To return to the front end like this, each data object contains fields, model, and PK, representing fields, model, and primary keys respectively. I prefer a dictionary object that contains only all fields.
The back end modifies each Model object to a dict dictionary object
from django.core import serializers
from django.http.response import JsonResponse
from django.forms.models import model_to_dict
# ex: /assetinfo/test_ajax
class TestAjax(View):
def get(self,request):
"""Display HTML page"""
return render(request,'assetinfo/test_ajax.html')
def post(self,request):
"""Receive POST requests to handle Ajax"""
# and the front-end convention return format
result = {"resCode": '0'."message": 'success'."data": []}
# query server information
servers = ServerInfo.objects.all()
Turn model objects into dict dictionaries one by one and set them to the list of data
for server in servers:
server = model_to_dict(server) # model object to dict dictionary
server['server_used_type_id'] = serializers.serialize('python', server['server_used_type_id']) # Foreign key model objects need to be serialized, or removed without passing
result["data"].append(server)
return JsonResponse(result)
Copy the code
The browser tests are as follows:
As you can see, this is passed to the front end as a dictionary object.
Finally, an example of front-end JS traversing JSON data is given.
Sample jSON-formatted data returned by the front-end traversal
<script>
$(function() {$('#search_server').click(function() {... // Send an Ajax post request $. Ajax ({url:"/assetinfo/test_ajax".type: 'POST',
data: {
"tag": "search_project"."server_name": server_name,
},
dataType: "json",
async: false// Call the function success:function (res) {
{#console.log(res.data); #}// Iterate over the datafor(var i=0; i<res.data.length; i++){ console.log(res.data[i]); console.log(res.data[i]['server_hostname']);
console.log(res.data[i]['server_internet_ip']);
console.log(res.data[i]['server_intranet_ip']); }}, // call error when request error:function () {
alert("Failed to query project data send");
}
})
})
})
</script>
Copy the code
The following information is displayed: