My First Django Project (2)

1. 接下来是比较重要的VIEWS.py,您将会比较多的时间在这.有点想.net里面的aspx的cs概念,而aspx就是和接下来要创建的template html相似!

下面是我创建的一个view def.

from django.shortcuts import render, render_to_response
def
alert(request): posts = AlertMaster.objects.all() #这里的alertmaster一个表的对象,这里是输出他的所有对象 return render_to_response('external.html',{'posts':posts}) #第一个参数是要使用的模板名称。第二个参数,是为该模板创建 Context 时所使用的字典
文件夹结构:

│ admin.py │ models.py <-----------------model数据类 │ tests.py │ views.py<-------------------views - controller - 用于定义def返回请求页面和context │
__init__.py │ ├─migrations │ __init__.py │ __init__.pyc │ ├─static <--------------------------------用去存放css或者js之类的文件夹 │ │ body.css │ │ jquery-1.8.2.min.js └─templates <-------------------------------此地方用来存放模板   ajax.html <------------------------------ajax请求返回模板   alert.html <----------------------------主模板   external.html<--------------------------extended模板

2.1 external.html

{% extends "alert.html" %}       #继承主模板alert.html
{% block content %}
        {%  for post in posts %}
            <tr>
                <td>{{post.production_day}}</td> 
                <td>{{post.silo}}</td> 
                <td>{{post.server}}</td> 
                <td>{{post.region}}</td> 
                <td>{{post.service}}</td> 
                <td>{{post.osm}}</td> 
                <td>{{post.pap}}</td> 
                <td>{{post.sla}}</td>
            </tr>
{%endfor%}
{% endblock %}    

2.2 alert.html

<table style="clear:both;" class="altrowstable" id="alternatecolor">
{%block content%}{% endblock%}          #此处预留给extended.html,方便模板的拼接和可拓展
</table> 

3. ajax 请求 views.py

jquery/ajax 代码:

$.post("/ajax_response/", {"param": a,"param1":b,"param2":c}, function (data) {          #URL部分"/ajax_response/"将在urls.py中重定向
 $("#alternatecolor").html(data); });

Urls.py 代码:

     url(r'^alert/$', alert),     # 将进入views.py 中 def alert:
   url(r'^ajax_response/$',ajax_response), #ajax URL定义(如上块ajax请求URL所定义),返回views.py中定义的def ajax_response 方法(如下块代码)

views.py ajax controller 代码:

def ajax_response(request): 
    param=request.POST.get("param") #获取由模板ajax传来的参数
    raw_sql='select * from alert.alert_master where param= "'+param+'"'
    tests  =  AlertMaster.objects.raw(raw_sql) #执行rawsql
    return render_to_response('ajax.html',{'tests':tests}) #返回带新字典的ajax页面(html)
原文地址:https://www.cnblogs.com/kiddy/p/4423469.html