原创作品,允许转载,转载时请务必以超链接形式标明文章原始出处 、作者信息和本声明。否则将追究法律责任。http://twentyfour.blog.51cto.com/945260/711249
- Django---》“最适合开发有限期的完美web框架”1、创建项目
- [root@alibaba-taobao ~]# django-admin.py startproject mysite
- [root@alibaba-taobao ~]# cd mysite && ls
- __init__.py manage.py settings.py urls.py
2、运行开发服务器dev- [root@alibaba-taobao mysite]# python manage.py runserver 0.0.0.0:8080
- Validating models...
- 0 errors found
- Django version 1.3, using settings 'mysite.settings'
- Development server is running at http://0.0.0.0:8080/
- Quit the server with CONTROL-C.
- [10/Nov/2011 02:11:59] "GET / HTTP/1.1" 200 2051
- [10/Nov/2011 02:12:00] "GET / HTTP/1.1" 200 2051
2.3、创建blog项目- [root@alibaba-taobao mysite]# python manage.py startapp blog
- [root@alibaba-taobao mysite]# ll blog/
- total 12
- -rw-r--r-- 1 root root 0 Nov 10 16:14 __init__.py
- -rw-r--r-- 1 root root 57 Nov 10 16:14 models.py
- -rw-r--r-- 1 root root 383 Nov 10 16:14 tests.py
- -rw-r--r-- 1 root root 26 Nov 10 16:14 views.py
把blog这个app以模块的形式添加到settings.py文件的INSTALLED_APPS元组中,声明使用该app- INSTALLED_APPS = (
- 'django.contrib.auth',
- 'django.contrib.contenttypes',
- 'django.contrib.sessions',
- 'django.contrib.sites',
- 'django.contrib.messages',
- 'django.contrib.staticfiles',
- 'mysite.blog', ##注意有个逗号
- # Uncomment the next line to enable the admin:
- # 'django.contrib.admin',
- # Uncomment the next line to enable admin documentation:
- # 'django.contrib.admindocs',
- )
2.4、设计模型来定义blog数据结构(这是基于django的blog应用核心部分)- [root@alibaba-taobao blog]# vim models.py
- # Create your views here.
- from django.db import models
- class BlogPost(models.Model):
- title = models.CharField(max_length=150)
- body = models.TextField()
- timestamp = models.DateTimeField()
博客很简单:就标题、内容、时间三块2.5、设置连接数据库mysql- [root@alibaba-taobao mysite]# /etc/init.d/mysqld start
- Starting MySQL: [ OK ]
- [root@alibaba-taobao mysite]# mysql -uroot -palibaba
- mysql> create database blog;
- Query OK, 1 row affected (0.00 sec)
设置settings.py连接数据库- [root@alibaba-taobao mysite]# vim settings.py
- 。。。
- DATABASES = {
- 'default': {
- 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
- 'NAME': 'blog', # Or path to database file if using sqlite3.
- 'USER': 'root', # Not used with sqlite3.
- 'PASSWORD': 'alibaba', # Not used with sqlite3.
- 'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
- 'PORT': '', # Set to empty string for default. Not used with sqlite3.
- }
- }
通过定义好的数据结构来生成表数据,- [root@alibaba-taobao mysite]# 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 auth_message
- Creating table django_content_type
- Creating table django_session
- Creating table django_site
- Creating table blog_blogpost
- 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 'root'): root
- E-mail address: zhipeng.wangzp@alibaba-inc.com
- Password:
- Password (again):
- Superuser created successfully.
- Installing custom SQL ...
- Installing indexes ...
- No fixtures found.
由于在INSTALLED_APPS默认开启了django.contrib.auth,所以提示创建auth系统用户,反正下面用到,所以提前创建好用户root:alibaba- [root@alibaba-taobao mysite]# !mysql
- mysql -uroot -palibaba
- Welcome to the MySQL monitor. Commands end with ; or \g.
- Your MySQL connection id is 268
- Server version: 5.0.77 Source distribution
- Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
- mysql> use blog;
- Reading table information for completion of table and column names
- You can turn off this feature to get a quicker startup with -A
- Database changed
- mysql> show tables;
- +----------------------------+
- | Tables_in_blog |
- +----------------------------+
- | auth_group |
- | auth_group_permissions |
- | auth_message |
- | auth_permission |
- | auth_user |
- | auth_user_groups |
- | auth_user_user_permissions |
- | blog_blogpost |
- | django_admin_log |
- | django_content_type |
- | django_session |
- | django_site |
- +----------------------------+
- 12 rows in set (0.00 sec)
- mysql> desc blog_blogpost;
- +-----------+--------------+------+-----+---------+----------------+
- | Field | Type | Null | Key | Default | Extra |
- +-----------+--------------+------+-----+---------+----------------+
- | id | int(11) | NO | PRI | NULL | auto_increment |
- | title | varchar(150) | NO | | NULL | |
- | body | longtext | NO | | NULL | |
- | timestamp | datetime | NO | | NULL | |
- +-----------+--------------+------+-----+---------+----------------+
- 4 rows in set (0.01 sec)
可以看到通过定义的数据结构生成了数据表。这里的ID是自动生成的。2.6、设置admin应用(用于CRUD,即便于create read update delete)首先在settings.py的INSTALLED_APPS元组中启用'django.contrib.auth'- INSTALLED_APPS = (
- 'django.contrib.auth',
- 'django.contrib.contenttypes',
- 'django.contrib.sessions',
- 'django.contrib.sites',
- 'django.contrib.messages',
- 'django.contrib.staticfiles',
- 'mysite.blog',
- 'django.contrib.admin', #注意逗号
- # Uncomment the next line to enable the admin:
- # 'django.contrib.admin',
- # Uncomment the next line to enable admin documentation:
- # 'django.contrib.admindocs',
- )
运行syncdb把新添加的应用生成数据表- [root@alibaba-taobao mysite]# python manage.py syncdb
- Creating tables ...
- Creating table django_admin_log
- Installing custom SQL ...
- Installing indexes ...
- No fixtures found.
再次去查看tables的话可以发现多了django_admin_log这张表到目前为止,数据表结构和admin应用的做好了,往下要设定一个URL来访问该应用- [root@alibaba-taobao mysite]# vim urls.py
- from django.conf.urls.defaults import patterns, include, url
- # Uncomment the next two lines to enable the admin:
- from django.contrib import admin
- admin.autodiscover()
- urlpatterns = patterns('',
- # Examples:
- # url(r'^$', 'mysite.views.home', name='home'),
- # url(r'^mysite/', include('mysite.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)),
- )
去掉蓝色部分前面的注释符号#,实现admin页面相应访问http://192.168.199.129:8080/admin/ 测试,这里是我的主机IP通过admin这个管理接口,还没看到blog应用,因为需要告诉django要在admin窗口显示上面制定好的模型,这里只需要在modules.py中导入admin应用即可:- [root@alibaba-taobao blog]# pwd
- /root/mysite/blog
- [root@alibaba-taobao blog]# vim models.py
- from django.db import models
- from django.contrib import admin
- class BlogPost(models.Model):
- title = models.CharField(max_length=150)
- body = models.TextField()
- timestamp = models.DateTimeField()
- admin.site.register(BlogPost)
好了,重新刷新页面即可。点击进去,添加博客:保存。这里还可以对admin的视图列表改进一下,只需在models.py中添加BlogPostAdmin类:- [root@alibaba-taobao blog]# vim models.py
- admin.site.register(BlogPost)
- from django.db import models
- from django.contrib import admin
- class BlogPost(models.Model):
- title = models.CharField(max_length=150)
- body = models.TextField()
- timestamp = models.DateTimeField()
- class BlogPostAdmin(admin.ModelAdmin):
- list_display = ('title','body','timestamp')
- admin.site.register(BlogPost,BlogPostAdmin)
刷新页面:顺便我们还可以修改TIME_ZONE为亚洲上海和LANGUAGE_CODE为zh_CN,到settings.py里修改即可到这里,后台管理、数据库后台都搞定了,但是对于一个博客还需要一个前台页面!
这里不谈及前端设计,所以丑丑也罢。。但至少要有!!2.8、建立blog公共部分(即前端显示)对于前端页面,从django角度讲,有三个典型的组件:一个模板(template):负责将传进来的信息显示出来,一般是Html页面一个视图函数(view):负责从数据库获取要显示的信息,替代了SQL语句。其实在上面把blog数据结构生成数据库表也是django底层处理的,替代了SQL语句。即为屏蔽的数据库层面,好处是数据库迁移之类的,便捷。一个URL模式:定义好被访问的URL,可不是管理后台的URL哦!2.8.1、创建模板- [root@alibaba-taobao blog]# cat templates/archive.html
- {% block content %}
- {% for post in posts %}
- <h1>{{ post.title}}</h1>
- <p>{{ post.timestamp}}</p>
- <p>{{ post.body }}</p>
- {% endfor %}
通过变量标签和块标签实现blog文章一篇篇显示,没涉及到翻页!对于archive.html的命名随意,但是对于新创建的templates目录则强制设定的,因为django在默认情况下会在搜索模板的时候查看应用程序下的每个templates目录。2.8.2、创建一个视图函数(应该说,这里头也就只有视图函数才见到python)该视图函数用于从数据库读取所有blog文章,并用上面的模板显示出来- [root@alibaba-taobao blog]# vim views.py
- # Create your views here.
- from django.template import loader,Context
- from django.http import HttpResponse
- from mysite.blog.models import BlogPost
- def archive(request):
- posts = BlogPost.objects.all()
- t = loader.get_template("archive.html")
- c = Context({'posts':posts})
- return HttpResponse(t.render(c))
2.8.3、创建URL- [root@alibaba-taobao mysite]# vim urls.py
- from django.conf.urls.defaults import patterns, include, url
- # Uncomment the next two lines to enable the admin:
- from django.contrib import admin
- admin.autodiscover()
- from mysite.blog.views import *
- urlpatterns = patterns('',
- # Examples:
- # url(r'^$', 'mysite.views.home', name='home'),
- # url(r'^mysite/', include('mysite.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'^blog/$', archive),
- )
这里的流程是这样的:访问http://192.168.199.129:8080/blog/ 被指向archive函数,该函数在mysite.blog.views下定义的,所以才在上面import的,通过views.py定义的内容从数据库获取内容并返回给client者。至于这里python和正则定义的内容不多解释了,django开发指南讲述比较清楚。到这里,这个blog就算是完成好了。如果说要把页面做个美化之类的,那是前端的事情咯。继续添加文章:
- [root@alibaba-taobao ~]# tree mysite
- mysite
- |-- __init__.py
- |-- __init__.pyc
- |-- blog
- | |-- __init__.py
- | |-- __init__.pyc
- | |-- models.py
- | |-- models.pyc
- | |-- templates
- | | `-- archive.html
- | |-- tests.py
- | |-- views.py
- | `-- views.pyc
- |-- manage.py
- |-- settings.py
- |-- settings.pyc
- |-- urls.py
- `-- urls.pyc
- 2 directories, 15 files
说明:from 《django web开发指南》一书。。。有做过一些小改动。。
毕竟书有点旧了,因为django版本问题,会出现一些小问题。。。
不停的google就可以解决问题。。。
本文出自 “twenty_four” 博客,请务必保留此出处http://twentyfour.blog.51cto.com/945260/711249