第一个django应用回忆录(日报提交(或者是不能删除和修改的留言板?))

认真写了一大堆,突然说页面崩溃! 恼火。 ╭(╯^╰)╮ 可恶!!!博客园都没有隔几分钟自动备份的功能吗?!只好努力回想.


嗯工作暂时告一段落,趁还记得赶紧记下来.

首先,需要开发一个每天工作提交应用,有个列表页显示当前月每人每天提交的日报.显示一个列表,有标题和发表人,发表时间.点击标题进入详细页.暂时没有修改和删除功能.

 

创建项目

首先在通过cmd到D:\testsite下,输入: django-admin.py startproject dailyreport  就会看到在testsite文件夹下生成了一个dailyreport文件夹,打开文件夹有4个文件:

__int__.py    manage.py    settings.py   urls.py 

然后输入 python manage.py runserver 运行开发服务器.然后在浏览器输入127.0.0.0:8000 就会看到一个赏心悦目的 It worked! 页面, 耶~ 做到这的时候很开心,因为之前学习django和python都是在debian的无界面系统下,突然开始用window我居然不会操作了.☻ 

如果有这个页面说明..我认为算是一切顺利吧,如果没有就删掉重新来~

 

创建应用

在项目文件夹下输入 manage.py startapp viewblog ,会看到在项目文件夹下生成了一个文件夹叫做viewblog,里面有3个文件:

__int__.py    models.py    views.py

 

设计Model

也就是viewblog应用下的models.py文件. 打开之:

第一次打开显示 from django.db import models和一句注释

编辑后:

    #-*- coding:UTF-8 -*-
 
 from django.db import models

 #adminblog数据库
 
 class Author(models.Model):
FirstName = models.CharField(max_length=50)
LastName = models.CharField(max_length=50)
Email = models.EmailField(blank=True)

def __unicode__(self):
return '%s %s' % (self.FirstName , self.LastName)

 class DailyReport(models.Model):
DailyReport_Title = models.CharField(max_length=150)#标题
  DailyReport_Body = models.TextField()#内容
  DailyReport_Author = models.ForeignKey(Author)
DailyReport_Timestamp = models.DateTimeField()#汇报时间
 
     def __unicode__(self):
         return self.DailyReport_Title

 2张表,一个Author(作者表),一个Dailyreport(日报表)

设置数据库

我用的是SQLite,简单好用.首先修改项目根目录下的settings.py文件.用SQLite的话只要设置2个地方:

 先在代码最上方加入下面的代码,作用是活的当前文件夹路径 

import os
curpath=os.path.normpath(os.path.join(os.getcwd(),os.path.dirname(__file__)))


 然后找到下面2个设置并修改 

DATABASE_ENGINE = "sqlite3"
DATABASE_NAME
=os.path.join(curpath,'dev.db')

如果没有自己创建数据库文件,这时候就会发现在项目根目录下已经自动生成了dev.db

然后输入命令:manage.py syncdb,会看到很多类似Createing table auth_message的输出,然后会出现一个问题:

Would you like to create one now? (yes/no):

这个问题的意思是创建一个项目的超级用户,其实就是你自己,按照提示输入就好.name:root,pwq:root

(我开始觉得累了..)

 

创建模板

在项目目录下新建文件夹 templates. 然后通过settings.py告诉程序模板文件的地址:

找到TEMPLATE_DIRS修改后:

TEMPLATE_DIRS = (
os.path.join(curpath,
'templates').replace('\r\n','<br/>'),

然后在templates下新建一个主模板:

base.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>{% block title %}{% endblock %}</title>
<style type="text/css">
<!--
body
{
background-color
: #453;
color
:#efd;
padding
:0 5em;
margin
:0
}
.footer
{
font-size
: 14px;
color
: #333;
font-weight
: bold;
display
:block
}
.content
{
width
: 100%;
border-bottom
:#fff dotted 1px;
margin-top
:1em;
height
:30px;
}
.title
{
width
:70%;
float
:left;
display
:block;
}
.title a
{ text-decoration:none;
font-size
:20px;
color
:#bf8;}
.title a:hover
{
text-decoration
:underline;
font-size
:20px;
color
:#bf8;
}
.authortiem
{
width
:30%;
float
:right;
text-align
: right;
}
h1
{
padding
:2em 1em;
background-color
:#675
}
.content-title
{
text-align
: center;
font-size
: 20px;
font-weight
: bold;
}
.content-time
{
text-align
: right;
margin-right
:2em;
font-size
:14px;
}
.content-body
{
font-size
: 18px;
margin-left
:1em;
margin-right
:1em;
}
.back-list
{
float
:right;
margin-right
: 2em;
color
:#bf8;
}
-->
</style>
</head>
<body>
<h1>Daily Report</h1>
{% block content%}
{% endblock%}
<br />
<br />
<br />
<br />
<br />
</body>
</html>

这个里面包含了样式和类似title啊这样每个页面都必须有的公用代码~django果然好用 :)

然后继续创建一个子模板,用来显示列表页的:

list.html
<p>{% extends "base.html" %}
{% block title%}日报列表{% endblock %}
{% block content %}
</p>
<form action="self" method="post">
<p>选择月份(默认显示本月):
<label>
<select name="MonthSelect" id="MonthSelect">
{% for mon in listNew %}
<option value={{ mon }}>{{ mon }}</option>
{% endfor %}
</select>
</label><input type="submit" name="month" value="确定" /></label></p>
</form>
<br />
当前选择是:{{ today }}
<br />
<a href="/addlog" class="back-list">发表一篇新日报</a>
<br />
{% for log in logs%}

<div class="content">
<div class="title"><a href="/content?id={{ log.id }}">{{ log.DailyReport_Title }}<a/></div>
<div class="authortiem">{{ log.DailyReport_Author }} 发表于 {{ log.DailyReport_Timestamp }}</div>
</div>
<br />
{% endfor %}
{% endblock%}

 这个模板继承了base.html模板,然后有一些自己的内容...可以看到它需要传递来一些数据,{{数据}}

 

创建视图

最关键的地方 - - 在viewblog应用下编辑views.py

# -*- coding: utf-8 -*-
#
Create your views here.
from django.template import loader,Context
from django.http import HttpResponse
from dailyreport.viewblog.models import *
import datetime

def archive(request):
#start这部分代码是用来获得所有提交过日报的月份
listOld
= []
months
= DailyReport.objects.values('DailyReport_Timestamp').order_by("DailyReport_Timestamp")
for mon in months:
listOld.append( str(mon [
'DailyReport_Timestamp'].year) + '-' + str(mon ['DailyReport_Timestamp'].month))
d
={}
for ym in listOld:
if not d.has_key(ym):
d[ym]
=""
listNew
=[]
for key in d.keys():
listNew.append(key)
#end
#如果用户选择月份了的话
if 'MonthSelect' in request.POST and request.POST['MonthSelect']:
month
= request.POST['MonthSelect']
logs
= DailyReport.objects.filter(DailyReport_Timestamp__month=int(month.split('-')[0]),DailyReport_Timestamp__month=int(month.split('-')[1])).order_by("-DailyReport_Timestamp")
today
= month

#这个可以理解为用户第一次载入列表页,所以不会有月份的参数
else:
today
= datetime.datetime.now().month
logs
= DailyReport.objects.filter(DailyReport_Timestamp__month=datetime.datetime.now().month,DailyReport_Timestamp__year=datetime.datetime.now().year).order_by("-DailyReport_Timestamp")

t
= loader.get_template("list.html")
c
= Context({ 'logs':logs,'listNew':listNew,'today':today})
return HttpResponse(t.render(c))

 

创建URL模式

现在可以说是万事俱备只欠东风了,我们写好了模板和视图,需要配置好url模式,用户才能访问到.

打开项目目录下的urls.py,修改后:

from django.conf.urls.defaults import *
from dailyreport.viewblog.views import *

# Uncomment the next two lines to enable the admin:
#
from django.contrib import admin
#
admin.autodiscover()

urlpatterns
= patterns('',
(r
'^view/', archive),

然后runserver一下~在浏览器输入127.0.0.1:8000/view/ 就可以看到列表页了,不过还没有开发"添加"功能,所以也暂时忽略掉页面上的"发表一篇新日报"按钮..明天继续吧.

回头看看其实挺简单,可是当时为什么总被各种小问题卡主呢~

posted @ 2010-06-23 17:39  Phenix.  阅读(1183)  评论(2编辑  收藏  举报