一个用python和django写的小程序

这几天都在写一个程序,是在一个网络公司实习的时候叫做的练习。下面我程序的全部用到的代码和命令,以及一些说明,记在这里希望自己以后看到 还有也许对某些人有用,省点力气。也欢迎提建议帮助我进步。

python+django+sqlite3弄的

sqlite3只用了它的drop table 的命令,因为改了类的结构之后就会导致表的改变,要去数据库里面修改表,反正是练习干脆drop掉。

django-admin.py startproject new2       新建一个项目,
manage.py startapp myorder
建了一个app

然后修改settings.py

DATABASE_ENGINE = 'sqlite3'      .  数据库直接下载了一个sqlite3.exe很小的文件直接使用
DATABASE_NAME = '/.data2.db'      
这个data2.db的路径要写绝对路径了,我写了这个,d盘根目录下出现了个.data2.db文件  如果改了models就要在cmd里面写sqlite3 d:/.data2.db    然后写.tables 看到里面的table的名字,看了名字(我的是myorder_restitem  然后用drop table myorder_restitem命令把关于餐馆的类的表丢弃了,目前我sqlite3就会drop……后来改成了绝对路径DATABASE_NAME = 'd:/order/new2/data2.db'

TEMPLATE_DIRS 里面添加:
'./templates',      
在新建的工程文件夹里面建一个叫templates的文件夹,模版都在里面
INSTALLED_APPS
添加:
'new2.myorder',
后来出了一个什么unicode问题,就在末尾加了句:(虽然不太明白啥意思)
FILE_CHARSET = "gb2312"


然后去修改新建的myorder app
里面的models放了三个类  把该appmodels.py文件改成了下面这样,
http://www.djangoproject.com/
Each model is a Python class that subclasses django.db.models.Model.
Each attribute of the model represents a database field.
):

from django.db import models
   
class restItem(models.Model)    :
    restName = models.CharField(maxlength=20)
    restTel = models.IntegerField()
    restAddress = models.CharField(maxlength=30)
   
class orderItem(models.Model):
    workerName = models.CharField(maxlength=10)
    dishName = models.CharField(maxlength=20)
    dishPrice = models.FloatField()
    orderTime = models.DateTimeField(auto_now=True) #
自动记录该条实例创建的时间,不用自己赋值
    orderRest = models.ForeignKey(restItem)   

class dishItem(models.Model):   
    dishName = models.CharField(maxlength=20)
    dishPrice = models.FloatField()
    dishRest = models.ForeignKey(restItem)
    dishTime = models.DateTimeField(auto_now=True) 

manage.py syncdb
初始化数据库,没有什么特别的,照提示做

manage.py runserver 运行  如果是写成manage.py runserver 0.0.0.0:8000就可以让其他ip访问这个服务,端口是8000,可以改成别的端口,不写ip就只能自己访问自己http://127.0.0.1:8000/


改本项目下面的urls.py为:
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    # Example:
    # (r'^new2/', include('new2.foo.urls')),
    (r'^inputorder/$', 'new2.myorder.views.inputOrder'),
    (r'^statistic/$', 'new2.myorder.views.statistic'),
    (r'^selectlist/$', 'new2.myorder.views.selectList'),
    (r'^editorder/$', 'new2.myorder.views.editOrder'),
    # Uncomment this for admin:
#     (r'^admin/', include('django.contrib.admin.urls')),
)
中间添加的那些是url与相应的函数响应
那些响应都是在myorder app views.py里面的

views.py里面添加函数:
# Create your views here.
#coding=utf-8
from new2.myorder.models import *
#把自己的那几个类放进去,下面几个是可能用到的djangopython的东西
from django.template import loader, Context
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from datetime import *

def inputOrder(request):
    text = 'no blank!'
    if
request.GET.has_key('wName')  :  
        wName =
request.GET['wName'] #request是一个网络响应,一个数据包,里面是固定格式的数据
        dName = request.GET['dName']
        dPrice = request.GET['dPrice']
        rName = request.GET['rName']
       
       
        if (wName and dName and dPrice and rName ):
           
try:
                orderRest = restItem.objects.get(restName=rName)
# restItem.objects.get(条件)如果符合条件的不止一个就出错,还要看看是不是不存在,不存在也出错
           
except restItem.DoesNotExist:
                text='new restItem added'
                newRest = restItem(restName=rName,restTel='new',restAddress='new')
                newRest.save()
#保存数据,添加到数据库里面了
                orderRest=newRest
                newDish = dishItem(dishName=dName,dishPrice=dPrice,/
                                dishRest=newRest)
                newDish.save()
            try:
                orderDish = dishItem.objects.get(dishName=dName,dishRest=orderRest) 
            except dishItem.DoesNotExist:
                newDish = dishItem(dishName=dName,dishPrice=dPrice,/
                                dishRest=orderRest)                         
                newDish.save()
               
            newOrder= orderItem(workerName=wName,dishName=dName,/
                           dishPrice=dPrice,orderRest=orderRest)
            newOrder.save()              
            text = 'New Order Is Added ! !'              
      
    orderList =
orderItem.objects.order_by('-id')   #排序
   
   
return render_to_response('myorder/inputorder.htm',{'orderItems':orderList,'sendMessage':text})   
#把一个字典{'orderItems':orderList,'sendMessage':text}传给模版文件,字典的条目'orderItems' 'sendMessage' 就是在网页当中django引用的名字
   

   

def statistic(request):
    toShowList = []
    totalAll=0
    total = 0
    #if request.method == 'POST' :
    workerList =
orderItem.objects.values('workerName').distinct()#workerName这个条目在数据库里面的值都列出来,非重复的值
       
    for worker in workerList:
        orderList =
orderItem.objects.filter(workerName=worker['workerName'])#filter函数
        for order in orderList :
            total = total + order.dishPrice
        toShowList
.append({'workerName':worker['workerName'],'total':total})   
        totalAll=total+totalAll           
        print total,totalAll
        total=0
        #print toShowList[0]['workerName']
    return render_to_response('myorder/statistic.htm',{'toShowList':toShowList,'all':totalAll})   
      
      
def selectList(request):
    #return HttpResponse('xxx')
    sel_list =''
    dobjects=[]
    orderItems=[]
    message='no blank !'
   
    if request.GET.has_key('sel_list'):
        sel_list=request.GET['sel_list']
        #print sel_list
        rest=restItem.objects.get(id=sel_list)
        dobjects=dishItem.objects.filter(dishRest=rest)
    if request.GET.has_key('yourNameForSel'):   
        yourNameForSel=request.GET['yourNameForSel']
        orderItems=orderItem.objects.order_by('-id')
        if yourNameForSel:
            dishChoose =
dict(request.GET)['dishChoose']#request获得的复选框的数据(条目id),强制转换成列表以便后面用
            if  dishChoose:  
                dishToAdd=
dishItem.objects.in_bulk(dishChoose).values()#in_bulk返回的是id为条目,实例为值的一个字典列   .values()就是把它的值,也就是实例都取出来成一个列表,以便下面用
                for dish in dishToAdd:
                    newOrder = orderItem(workerName=yourNameForSel,dishName=dish.dishName,/
                                 dishPrice=dish.dishPrice,orderRest=dish.dishRest)
                    newOrder.save() 
                    message='New order added !'
                    orderItems=orderItem.objects.order_by('-id') 
    else :  
        message='no blank !'             
    robjects=
restItem.objects.all()
    return render_to_response('myorder/selectlist.htm',{'robjects':robjects,/
                            'dobjects':dobjects,'message':message,'orderItems':orderItems})   
    

def editOrder(request)    :
    orderItems=[]
    orderItems=orderItem.objects.order_by('-id')
    if request.GET.has_key('editorder'): 
        editorder=request.GET['editorder']
        if editorder:
            editorder = dict(request.GET)['editorder']
            orderdels=orderItem.objects.in_bulk(editorder).values()
            for orderdel in orderdels:
                orderdel
.delete()
            orderItems=orderItem.objects.order_by('-id')            
    return render_to_response('myorder/editorder.htm',{'orderItems':orderItems})   
    

 

templates文件夹下面添加对应的.html文件 inputorder 我是在templates里面又建了myorder文件夹,所有的myorder用的都在里面放着

base.htm里面想插入变动代码的地方放:
 {% block content1 %}
 {% endblock %} 

 下面是我的模版文件:

base.htm


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>
定餐</title>
</head>
<body>
<a href="/inputorder/">
手工输入</a>
<a href="/selectlist/">
从菜单选择</a>
<a href="/statistic/">
统计总价</a>
<a href="/editorder/">
删除订单</a>


 {% block content1 %}
 {% endblock %} 


</body>
</html>

selectlist.htm

{% extends "myorder/base.htm" %}
{% block content1 %}

<form action="/selectlist/" method="get">
<table  border="1">
  <tr>
    <td width="120" >&nbsp;
      <input type="submit" name="Submit" value="
选择菜单"></td>

 <td width="120"><select name="sel_list">
  
   {% for robject in robjects  %}
   <option value="{{robject.id}}">{{robject.restName}}</option>
   {% endfor%}
 </select></td>
  </tr>
</table>
</form>

{%if dobjects%}
<form action="" method="get">
<table width="508" border="1">
  <tr>
    <td width="120">
输入名字:</td>
    <td><input type="text" name="yourNameForSel" size="15" maxlength="10"></td>
    <td colspan="5">&nbsp;</td>
  </tr>
  <tr>
    <td><input type="submit" name="Submit" value="
提交"></td>
    <td>&nbsp;{{message}}</td>
    <td colspan="5">&nbsp;</td>
  </tr>
  <tr>
    <td>
选择</td>
    <td>
菜名</td>
    <td colspan="5">
价格</td>
  </tr>
  {%for dobject in dobjects %}
  <tr>
 
    <td width="120"><input type="checkbox" name="dishChoose" value="{{dobject.id}}"></td>
    <td width="120">&nbsp;{{dobject.dishName}}</td>
    <td width="120" colspan="5">&nbsp;{{dobject.dishPrice}}</td>
 
  </tr>
  {%endfor%}

</table>

 

</form>
{%endif%}

 

{%if orderItems %}
<table border="1">
  <tr>
    <td width="50" >&nbsp;ID</td>
    <td width="100" >&nbsp;
员工</td>
    <td width="200" >&nbsp;
菜名</td>
    <td width="50" >&nbsp;
价格</td>
    <td width="100" >&nbsp;
餐厅</td>
    <td width="100" >&nbsp;
时间</td>
  </tr>
  {% for orderItem in orderItems %}
  <tr>
    <td width="50" >&nbsp;{{ orderItem.id }}</td>
    <td width="100" >&nbsp;{{ orderItem.workerName }}</td>
    <td width="200" >&nbsp;{{ orderItem.dishName }}</td>
    <td width="50" >&nbsp;{{ orderItem.dishPrice }}</td>
    <td width="100" >&nbsp;{{ orderItem.orderRest.restName }}</td>
    <td width="100" >&nbsp;{{ orderItem.orderTime }}</td>
  </tr>
 {% endfor %}
</table>
{%endif%}
{% endblock %} 

 

inputorder.htm

{% extends "myorder/base.htm" %}
{% block content1 %}
<form action="/inputorder/" method="get">
<table  border="1">
  <tr>
    <td width="180">&nbsp;
员工名:<input name="wName" type="text" value="" size="8" maxlength="8"></td>
    <td width="260">&nbsp;
菜名:<input name="dName" type="text" value="" size="20" maxlength="20"></td>
    <td width="150">&nbsp;
价格:<input name="dPrice" type="text" value="" size="8" maxlength="8"></td>
 <td width="150">&nbsp;
餐馆:<input name="rName" type="text" value="" size="10" maxlength="10"></td>
    </tr>
  <tr>
    <td colspan="4">&nbsp;{{sendMessage}}</td>
    </tr>
  <tr>
    <td><input type="submit" name="Submit_order" value="
提交"></td>
    <td>&nbsp;</td>

    <td>&nbsp;</td>
    <td>&nbsp; </td>

 
    </tr>

</table>

</form>

<table border="1">
  <tr>
    <td width="50" >&nbsp;ID</td>
    <td width="100" >&nbsp;
员工</td>
    <td width="200" >&nbsp;
菜名</td>
    <td width="50" >&nbsp;
价格</td>
    <td width="100" >&nbsp;
餐厅</td>
    <td width="100" >&nbsp;
时间</td>
  </tr>
  {% for orderItem in orderItems %}
  <tr>
    <td width="50" >&nbsp;{{ orderItem.id }}</td>
    <td width="100" >&nbsp;{{ orderItem.workerName }}</td>
    <td width="200" >&nbsp;{{ orderItem.dishName }}</td>
    <td width="50" >&nbsp;{{ orderItem.dishPrice }}</td>
    <td width="100" >&nbsp;{{ orderItem.orderRest.restName }}</td>
    <td width="100" >&nbsp;{{ orderItem.orderTime }}</td>
  </tr>
 {% endfor %}
</table>

{% endblock %} 


statistic.htm


{% extends "myorder/base.htm" %}
{% block content1 %}
<table  border="1">
  <tr>
    <td width="150">
员工</td>
    <td width="150">
个人总价</td>
  </tr>
 
  {%for item in toShowList %}
  <tr>
    <td>&nbsp;{{item.workerName}}</td>
    <td>&nbsp;{{item.total}}</td>
  </tr>
  {%    endfor  %}
 
</table>
<table border="1">
  <tr>
    <td width="150">&nbsp;</td>
    <td width="150">
公司总价</td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td>&nbsp;{{all}}</td>
  </tr>
</table>

{% endblock %} 

editorder.htm

{% extends "myorder/base.htm" %}
{% block content1 %}
  {%if orderItems %}
<form name="form1" method="get" action="/editorder/">
<table width="600" border="1">
  <tr>
    <td  width="50"><input type="submit" name="Submit" value="
删除"></td>
    <td  width="50">&nbsp;</td>
    <td  width="50">&nbsp;</td>
    <td  width="50">&nbsp;</td>
    <td  width="50">&nbsp;</td>
    <td  width="50">&nbsp;</td>
    <td width="50" >&nbsp;</td>
  </tr>
  <tr>
    <td width="50">
选择</td>
    <td  width="50">ID</td>
    <td  width="50">
员工名</td>
    <td  width="50">
菜名</td>
    <td  width="50">
价格</td>
    <td  width="50">
餐馆</td>
    <td  width="50">
时间</td>
  </tr>
 

    {% for orderItem in orderItems %}
  <tr>
    <td><input type="checkbox" name="editorder" value="{{ orderItem.id }}"></td>
    <td width="50" >&nbsp;{{ orderItem.id }}</td>
    <td width="100" >&nbsp;{{ orderItem.workerName }}</td>
    <td width="200" >&nbsp;{{ orderItem.dishName }}</td>
    <td width="50" >&nbsp;{{ orderItem.dishPrice }}</td>
    <td width="100" >&nbsp;{{ orderItem.orderRest.restName }}</td>
    <td width="100" >&nbsp;{{ orderItem.orderTime }}</td>
  </tr>
   {% endfor %}
</table>

</form>
{%endif%}


{% endblock %} 

如果不想直接用form action也可以
function showList(){
document.formOrder.action="/order/showlist/";
document.formOrder.submit();
}
buttononKeyup()函数调用

 

花了一个星期写成这个样子,开始的时候就一个模版,所有的函数都挤在里面,被头头说应该分开写才是正确的写代码的风格,从一窍不通,到通了一个缝%%&……


费了半天劲try to use
django-admin.py runserver --settings=mysite.settings

结果是应该设置
set PYTHONPATH=d:/order
set DJANGO_SETTINGS_MODULE=newtest.settings

我却
>>> import sys
>>> sys.path.append('D://order//newtest')
>>> sys.path

 

 

 
展开阅读全文

没有更多推荐了,返回首页