7
2012
练习创建wiki,留言板功能,使用django的app功能
在djangotest1目录下创建应用
./manage.py startapp wikitest
进入wikitest文件夹,自动生成文件如下:
wikitest/
__init__.py
models.py
views.py
tests.py
修改urls.py,添加
urlpatterns += patterns(”,
url(r’^wiki/$’,'wikitest.views.index’),
url(r’^wiki/(?P<pagename>\w+)/$’,'wikitest.views.index’),
url(r’^wiki/(?P<pagename>\w+)/edit/$’,'wikitest.views.edit’),
url(r’^wiki/(?P<pagename>\w+)/save/$’,'wikitest.views.save’),
)
编辑models.py
from django.db import models
# Create your models here.
class wiki(models.Model):
”’wiki model file”’
pagename = models.CharField(max_length=20,unique=True)
content = models.TextField()
编辑views.py
rom wikitest.models import wiki
from django.template import loader,Context
from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import render_to_response
def index(request,pagename=”"):
”’显示页面,为页面的文字做特殊的连接处理”’
if pagename:
pages = wiki.objects.filter(pagename=pagename)
if pages:
return process(‘wiki/page.html’,page[0])
else:
return render_to_response(‘wiki/edit.html’,{‘pagename’:pagename})
else:
page = wiki.objects.get(pagename=’FrontPage’)
return process(‘wiki/page.html’,page)
def edit(request,pagename):
page = wiki.objects.get(pagename=pagename)
return render_to_response(‘wiki/edit.html’,{‘pagename’:pagename,’content’:page.content})
def save(request,pagename):
content = request.POST['content']
pages = wiki.objects.filter(pagename=pagename)
if pages:
pages[0].content = content
pages[0].save()
else:
page = wiki(pagename=pagename,content=content)
page.save()
return HttpResponseRedirect(‘/wiki/%s’ %pagename)
import re
r = re.compile(r’\b(([A-Z]+[a-z]+){2,})\b’)
def process(template,page):
t = loader.get_template(template)
content = r.sub(r’<a href=”wiki/\1″>\1</a>’,page.content)
content = re.sub(r’[\n\r]+’,'<br/>’,content)
c = Context({‘pagename’:page.pagename,’content’:content})
return HttpResponse(t.render(c))
修改settings.py,在INSTALLED_APPS中添加
‘wikitest’,
执行
./manage.py syncdb
在templates/wiki/中添加
page.html
<h2>{{ pagename }} <h2>
<p>{{ content|safe }} </p>
<hr />
<p><form method=”post” action=”/wiki/{{ pagename }}/edit/” >
<input type=”submit” value=”edit” />
</form></p>
edit.html
<h2> Edit: {{ pagename }} </h2>
<form method=”post” action=”/wiki/{{ pagename }}/save/”>
<textarea name=”content” rows=10 cols=50>{{ content }} </textarea>
<input type=”submit” value=”save” />
</form>
此时可以通过地址
本文连接地址: http://www.fresker.com/old2/archives/525 (转载注明出处)
目前暂无评论