一、程序框架
1、结构图
2、settings.py
1)指明templates路径
import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) TEMPLATE_DIRS = ( os.path.join(BASE_DIR, 'templates'), )
2)修改数据库连接
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'django_db', 'USER': 'root', 'PASSWORD': 'feng', 'HOST': '127.0.0.1', 'PORT': '3306', } }
二、源码(MVC)
1、urls.py
from django.conf.urls import patterns, url, include urlpatterns = patterns('', (r'^latest_books/$', 'django_web_app.views.latest_books'), )
2、models.py——M
from django.db import models class Book(models.Model): name = models.CharField(max_length=50) pub_date = models.DateField()
1)创建django_db数据库
2)ctrl+alt+r:sql
3)ctrl+alt+r:syncdb
同步到数据库
运行后控制台输出结果:
Creating tables ... Creating table django_admin_log Creating table auth_permission Creating table auth_group_permissions Creating table auth_group Creating table auth_user_groups Creating table auth_user_user_permissions Creating table auth_user Creating table django_content_type Creating table django_session Creating table django_web_app_book 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 'administrator'): admin Email address: edisonfeng1988@gmail.com Warning: Password input may be echoed. Password: admin Warning: Password input may be echoed. Password (again): admin Superuser created successfully. Installing custom SQL ... Installing indexes ... Installed 0 object(s) from 0 fixture(s) Process finished with exit code 0
运行后的数据库结构:
PS:实际上可以重复执行以上动作,原先已经创建且录入数据的表不会被覆盖。
3、latest_books.html——V
<html><head><title>Books</title></head> <body> <h1>Books</h1> <ul> {% for book in book_list %} <li>{{ book.name }}</li> {% endfor %} </ul> </body></html>
4、views.py——C
#coding:utf-8 from django.shortcuts import render_to_response from models import Book def latest_books(request): #倒叙获取最新出版的10本书 book_list = Book.objects.order_by('-pub_date')[:10] return render_to_response('latest_books.html', {'book_list': book_list})
三、测试
1、录入测试数据
2、配置测试初始页面
3、运行结果:
附:由于内置应用服务器默认只能本机连接,若需要从其他ip访问,需要修改如下设置:
如果urls.py中没有映射任何视图,访问8000端口时会跳到django欢迎页面:
from django.conf.urls import patterns, url, include urlpatterns = patterns('', )