djangoview returns html page, the data transfer method of Django front and back

1. view -> HTML

Pass some data to html in the background and render it directly on the web page. This method can pass various data types, including list, dict, etc.

from django.shortcuts import render

def main_page(request):

data = [1,2,3,4]

return render(request, 'index.html', {'data': data})

html uses { { }} to get data

{ { data }}

2. view-> JavaScript

If the data is to be passed to js, ​​it will be wrong to write it in the above way.

Two points to note:

The values ​​in the function returned in views.py are processed with json.dumps()

Add a safe filter to the web page.

views.py

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

import json

from django.shortcuts import render

def main_page(request):

list = ['1', '2', '3']

return render(request, 'index.html', {

'List': json.dumps(list),

})

JavaScript part:

var List = { { List|safe }};

3. JavaScript Ajax dynamic page refresh

The front desk of the web page uses Ajax to send requests, processes the data in the background and returns the data to the front desk, and the front desk does not refresh the web page to dynamically load the data

JS sends an ajax request, processes the request in the background and returns status, result

Define a callback function after success: to process the returned data, you need to use JSON.parse(data)

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 代码:

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"]);

}

}

});

}

4. HTML->view

URL参数在view中传递

1、带参数名:通过named group方式传递指定参数,语法为: (?Ppattern), name 为传递参数的名称,pattern代表所要匹配的模式。如下:

url(r'^articles/(?P[0-9]{4})/(?P[0-9]{2})/$', views.month_archive)

中:year,month为参数名,而后面紧跟的则代表正则表达匹配的模式。

def month_archive(request,year,month):

print(year,month)

return render(request,"kingadmin/index.html",locals())

其中:app_name 和 model_name对应url中传递过来的参数值year值为:2017,month值为9

2、不带参数名:语法为: (r'pattern1/pattern2/'), pattern代表所要匹配的模式。如下:

url(r'^(\w+)/(\w+)/$', views.table_data_list)

def table_data_list(request,app_name,model_name):

admin_obj = base_admin.site.registered_sites[app_name][model_name]

return render(request,"kingadmin/table_data_list.html",locals())

其中:app_name 和 model_name对应url中传递过来的参数值app_name值为:crm,model_name值为customer

另外一个例子:

index.html

在应用polls里创建templates文件夹,再在里面创建polls文件夹,在新建的polls里创建index.html文件,打开并编写如下代码:

{% if latest_question_list %}

{% for question in latest_question_list %}

{ {question.question_text }}

{% endfor %}

{% else %}

No polls are available.

{% endif %}

上面代码是从views.py里分离出来的用来显示最近问题列表的功能,这里分条显示。

然后在polls的views里修改代码如下:

polls/views.py

from django.http import HttpResponse

from django.template import RequestContext,loader

from .models import Question

def index(request):

latest_question_list =Question.objects.order_by('-pub_date')[:5]

template =loader.get_template('polls/index.html')

context = RequestContext(request, {

'latest_question_list': latest_question_list,

})

returnHttpResponse(template.render(context))

这里用loader装载template:polls/index.html,然后再传递上下文给template进行render。

注意:Django新版本 path匹配正则时候无效,导入re_path即可匹配正则

from django.urls import re_path,path

urlpatterns = [

path('admin/', admin.site.urls),

re_path('edit/(\d+)',views.edit),

]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324143449&siteId=291194637