一、創建一個Django Projectcss
二、配置IDE的環境html
三、選擇django的版本號,先查看當前系統中的django版本號(IDE默認選擇1.2 or later)python
這裏默認使用sqlite,先使用默認的進行處理(有興趣的能夠改成mysql試試)mysql
默認生成的4個文件:sql
先跑起來看一下效果:數據庫
注意選擇Debug Configurations,選擇要運行的項目和主模塊(選擇項目根目錄下的manage.py便可)django
默認監聽的是8000,這裏修改成9000windows
控制檯上的信息:session
pydev debugger: startingoracle
四、修改配置文件settings.py
找到TIME_ZONE,修改成TIME_ZONE = 'Asia/Shanghai'
找到LANGUAGE_CODE修改成LANGUAGE_CODE = 'zh-CN'
# Django settings for demo project. DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'XXXXXXXXXXXXXXXXXX', # Or path to database file if using sqlite3. 'USER': 'XXXXXXXXX', # Not used with sqlite3. 'PASSWORD': 'XXXXXXXX', # 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. } } # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # On Unix systems, a value of None will cause Django to use the same # timezone as the operating system. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'Asia/Shanghai' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'zh-CN' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # If you set this to False, Django will not format dates, numbers and # calendars according to the current locale USE_L10N = True # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" MEDIA_URL = '' # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = '' # URL prefix for static files. # Example: "http://media.lawrence.com/static/" STATIC_URL = '/static/' # URL prefix for admin static files -- CSS, JavaScript and images. # Make sure to use a trailing slash. # Examples: "http://foo.com/static/admin/", "/static/admin/". ADMIN_MEDIA_PREFIX = '/static/admin/' # Additional locations of static files STATICFILES_DIRS = ( # Put strings here, like "/home/html/static" or "C:/www/django/static". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) # Make this unique, and don't share it with anybody. SECRET_KEY = 'e1=wpjck+9x5tppagmj78m!lep%h+g4z))$%=f&cl)_qihn(c!' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) ROOT_URLCONF = 'demo.urls' 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. ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'demo.blog', # Uncomment the next line to enable the admin: # 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', ) # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } }
五、創建一個blog app應用(也能夠在項目的windows中的目錄使用命令,效果是同樣)
六、修改settings.py,添加對blog的引用
找到INSTALLED_APPS,在尾部添加一行「demo.blog」(項目爲demo、應用爲blog)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'demo.blog',
)
七、打開blog/models.py,添加一個文章類:
from django.db import models from django.contrib import admin # Create your models here. class BlogPost(models.Model): title = models.CharField(max_length=150) body = models.TextField() timestamp = models.DateTimeField() class BlogPostAdmin(admin.ModelAdmin): list_display = ('title', 'timestamp') admin.site.register(BlogPost, BlogPostAdmin)
八、右擊項目,執行sync DB,在控制檯上可看到以下信息
九、修改settings.py,添加admin app
找到INSTALLED_APPS,在django.contrib.auth下一行添加'django.contrib.admin',
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.admin',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'demo.blog',
)
修改數據庫的鏈接(工程根目錄下的settings.py):
再執行一個sync DB
十、修改項目根目錄下的urls.py,去掉urlpatterns中最後一項對admin的註釋
(r'^admin/', include(admin.site.urls)),
---將最前面的「#」去掉便可,須要引入包「from django.contrib import admin」 在admin後面按下alt+/就能夠自動導入包了
在blog/models.py中,添加一行
admin.site.register(BlogPost)
查看一下項目運行的效果:
添加兩條數據後的效果顯示,有一些難看,待會進行修改
在blog/models.py添加一個ModelAdmin類
from django.db import models from django.contrib import admin # Create your models here. class BlogPost(models.Model): title = models.CharField(max_length=150) body = models.TextField() timestamp = models.DateTimeField() class BlogPostAdmin(admin.ModelAdmin): list_display = ('title', 'timestamp') admin.site.register(BlogPost, BlogPostAdmin)
刷新頁面,就變成下面這樣子了
十一、使用模板,顯示添加的數據
在blog目錄下創建一個名爲templates的目錄,在此目錄下創建一個名爲archive.html(demo/blog/templates/archive.html),輸入以下內容:
{% for post in posts %} {{ post.title }} {{ post.timestamp }} {{ post.body }} {% endfor %}
十二、打開blog的views.py,添加對視圖的控制
# Create your views here. from django.template import loader, Context from django.http import HttpResponse from demo.blog.models import BlogPost def archive(request): posts = BlogPost.objects.all().order_by("-timestamp") t = loader.get_template("archive.html") c = Context({ 'posts': posts }) return HttpResponse(t.render(c))
1三、在主urls.py中添加對blog的url匹配,在最後一行添加(r'^blog/', include('demo.blog.urls')),
from django.conf.urls.defaults import patterns, include # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'demo.views.home', name='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)), # (r'^blog/', include('demo.blog.urls')), (r'^admin/', include(admin.site.urls)), (r'^blog/', include('demo.blog.urls')), )
1四、在blog中新創建一個urls.py文件,添加以下內容
from django.conf.urls.defaults import * from demo.blog.views import archive urlpatterns = patterns('', url(r'^$', archive), )
如今的運行效果:
這個頁面有兩個問題:
一、沒有按發表的時間降序排列文章
二、界面太簡單,須要修飾一下
改進:
在blog/templates目錄下創建一個名爲base.html的頁面
<html> <head> <style type="text/css"> body { color: #efd; background: #453; padding: 0 5em; margin: 0 } h1 { padding: 2em 1em; background: #675 } h2 { color: #bf8; border-top: 1px dotted #fff; margin-top: 2em } p { margin: 1em 0 } </style> </head> <body> <h1>markGao's BLOG</h1> {%block content%} {%endblock%} </body> </html>
修改archive.html頁面
{% extends "base.html" %} {% block content %} {% for post in posts %} <h2>{{ post.title }}</h2> <p>{{ post.timestamp|date:"l, F jS" }}</p> <p>{{ post.body }}</p> {% endfor %} {% endblock %}
如今的界面漂亮一些了
修改<p>{{ post.timestamp }}</p>爲<p>{{ post.timestamp|date:"l, F jS" }}</p>
在blog/views.py中,將文章按時間降序排列(加一個」-」,不加則爲升序,還能夠添加按標題排序等)
posts = BlogPost.objects.all().order_by("-timestamp")