参考地址:http://www.informit.com/articles/printerfriendly.aspx?p=1273658
- 安装Python
- 安装数据库软件(Mysql)
- 安装Django
- 创建项目
- 创建应用
- 设计Model
- 修改数据库(mysql)配置
- 同步数据库
- 开启admin应用
- 修改View配置
- 修改Url配置
- 创建Template文件
- 测试项目
- 总结
- 附录
安装Python
安装过程略,安装完成后,在环境变量path中加上python目录。
安装后测试
打开python shell,输入import this ,如果提示zen of python则表示安装成功。
安装数据库软件(Mysql)
下载地址:http://dev.mysql.com/downloads/installer/
安装及配置过程略。
安装Django
下载地址:https://www.djangoproject.com/download/
下载完成后,解压下载的压缩文件,然后打开cmd命令行,cd到django目录,执行命令 python setup.py install
安装后检查
打开python shell,输入命令import django,如果没有traceback提示,则表示安装成功。
注:安装完成后,需要把django-admin.py(默认在\Python27\Lib\site-packages\django\bin\)添加到PATH中,以便以后调用。
创建项目
打开cmd命令行,cd到你需要放置项目的目录(例如E:),然后执行命令 django-admin.py startproject demo 执行之后便会在当前目录下看到新建的项目了。
项目目录结构
mysite
|-- mysite
|-- __init__.py
|-- settings.py
|-- urls.py
|-- wsgi.py
|-- manage.py
测试项目
在cmd命令行中cd到新建的项目文件夹中,执行命令manage.py runserver 8080,如果提示0 errors found,则表示项目启动成功。将命令行中提示的http地址拷贝到浏览器中,则可看到欢迎页面。
创建应用
在cmd命令行中执行命令manage.py startapp notice,执行完成后便会在项目根目录新建一个app文件夹。
App文件夹目录结构
Notice
|- __init__.py
|- models.py
|- tests.py
|- views.py
修改demo/settings.py文件,将新创建的应用(notice)加入到INSTALLED_APPS列表中。
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'notice',
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
设计Model
修改notice/models.py文件,创建NoticePost类。
from django.db import models
class NoticePost(models.Model):
title = models.CharField(max_length=3D150)
body = models.TextField()
postdate = models.DataTimeField()
class Meta:
ordering = ('-postdate',)
修改数据库(mysql)配置
修改demo/setting.py文件,修改DATABASES配置
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'test', # Or path to database file if using sqlite3.
'USER': 'root', # Not used with sqlite3.
'PASSWORD': '1', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost.
'PORT': '', # Set to empty string for default. .
}
}
同步数据库
注:在同步数据库之前要先在Mysql中创建test数据库
在cmd命令行中执行命令python manage.py syncdb,如果能够创建数据表,并且没有提示错误则表示执行成功。执行完毕后,可以在数据库中看到新建的数据表和管理员用户。
开启admin应用
修改demo/settings.py文件,去掉INSTALLED_APPS中'django.contrib.admin',的注释
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'notice',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
修改demo/urls.py文件,去掉admin相关的注释
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'demo.views.home', name=3D'home'),
# url(r'^demo/', include('demo.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
修改notice/models.py文件,在结尾处加入admin.site.register(NoticePost)
from django.db import models
from django.contrib import admin
class NoticePost(models.Model):
title = models.CharField(max_length=3D150)
body = models.TextField()
postdate = models.DateTimeField()
admin.site.register(NoticePost)
完成之后,需要重新同步一下数据库,如果提示django_admin_log表成功创建,则表示admin成功开启,这时可以起到项目python manage.py runserver ,然后在浏览器中输入http://127.0.0.1:8000/admin 即可看到管理员等人界面。输入在同步数据库时创建的管理员用户名和密码,即可登录到项目后台管理页面。
定制admin界面
可以尝试新建几个Notice,完成之后在notice post界面看到所有的notice都是同样的名称,而不是我们创建时的title。所以我们需要定制一下admin的显示。
修改notice/models.py文件
from django.db import models
from django.contrib import admin
class NoticePost(models.Model):
title = models.CharField(max_length=3D150)
body = models.TextField()
postdate = models.DateTimeField()
class Meta:
ordering = ('-postdate',)
class NoticePostAdmin(admin.ModelAdmin):
list_display = ('title','body','postdate')
admin.site.register(NoticePost,NoticePostAdmin)
修改完成后,再次刷新页面,就会看到所做的修改。
修改View配置
编辑文件notice/views.py
from django.template import loader, Context
from django.http import HttpResponse
from notice.models import NoticePost
def showallnotices(request):
postlist = NoticePost.objects.all() #获得所有的notice
t = loader.get_template("notice/notices.html") #与template中文件路径相同
c = Context({'postlist':postlist}) #与notices.html文件中变量名相同
return HttpResponse(t.render(c))
修改Url配置
在notice目录中新建urls.py文件(文件名可不同),编辑新建的urls.py文件
from django.conf.urls import patterns, include, url
from notice.views import showallnotices
urlpatterns = patterns('',
url(r'^$',showallnotices),) #此处为views中的函数
修改demo/urls.py文件
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'demo.views.home', name=3D'home'),
# url(r'^demo/', include('demo.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
url(r'^notice/',include('notice.urls')), #该处名称与notice目录中新建的文件名相同
)
创建Template文件
在项目根目录创建文件夹templates/notice/,修改demo/setting.py文件,修改TEMPLATE_DIRS,计入新建的templates目录
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
"F:\\Walkbox\\Python\\demo\\django\\demo\\templates ", # !! double \
)
在templates/目录中新建一个base.html文件,然后编辑base.html文件,输入如下内容。
<html>
<head><title>My Blog</title></head>
<body>
{% block content %}
{% endblock%}
</body>
</html>
在templates/notice/目录中创建一个notice展示页面notices.html,输入以下内容
{% extends "base.html" %}
{% block content %}
{% for post in postlist %}
<div>
<h2>{{post.title}}</h2>
<p>{{post.postdate}}</p>
<p>{{post.body}}</p>
<br />
</div>
{% endfor %}
{% endblock %}
测试项目
在浏览器中输入:http://127.0.0.1:8000/notice 即可看到我们用admin创建的notice。
总结
最好多写多思考,了解下各个部分的内在联系
附录
部分CMD命令执行过程:
F:\Walkbox\Python\demo\django>django-admin.py startproject demo
F:\Walkbox\Python\demo\django>cd demo
F:\Walkbox\Python\demo\django\demo>python manage.py runserver
Validating models...
0 errors found
Django version 1.4, using settings 'demo.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
[30/Oct/2012 14:40:20] "GET / HTTP/1.1" 200 1955
F:\Walkbox\Python\demo\django\demo>python manage.py startapp notice
F:\Walkbox\Python\demo\django\demo>python manage.py syncdb
Creating tables ...
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_user_permissions
Creating table auth_user_groups
Creating table auth_user
Creating table django_content_type
Creating table django_session
Creating table django_site
Creating table notice_noticepost
You just installed Django's auth system, which means you don't have any superusers defined.
Would you like to create one now? (yes/no): yes
Username (leave blank to use 'moose'): admin
E-mail address: admin@126.com
Password:
Password (again):
Superuser created successfully.
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)
F:\Walkbox\Python\demo\django\demo>python manage.py syncdb
Creating tables ...
Creating table django_admin_log
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)