環(huán)境搭建
1、下載所需的軟件包:
(1)python安裝包
(2)django安裝包
以下2個(gè)包其實(shí)是安裝python包管理工具,在后面安裝django文檔包模塊時(shí)會(huì)用到,下載網(wǎng)站是pypi
(1)setuptools.exe
(2)pip
2、安裝所需的軟件包:
python安裝包是exe,setuptools也是exe,所以直接雙擊安裝即可,先安裝
django、pip是python模塊包:安裝時(shí)先解壓,而后進(jìn)入目錄后使用命令:python setup.py install 安裝即可
3、測(cè)試python及django
python和setuptools因?yàn)槭莈xe安裝方式,已經(jīng)幫你添加了環(huán)境變量,安裝后可以直接使用
django、pip安裝后需要手動(dòng)把它們的安裝目錄添加到環(huán)境變量
新起cmd:輸入python,看到能進(jìn)入python交互解釋器則python沒有問題
輸入django-admin.py --help 能看到使用幫助提示則說明安裝成功
4、建立第一個(gè)django項(xiàng)目:
以下cmd命令會(huì)在當(dāng)前目錄下建立一個(gè)django項(xiàng)目djangoproject1:
django-admin.py startproject djangoproject1
這個(gè)項(xiàng)目目錄下有4個(gè)文件:
__init__.py manage.py ###功能與django-admin.py相同的文件,只是這個(gè)主要用于管理當(dāng)前項(xiàng)目 settings.py ###當(dāng)前項(xiàng)目的設(shè)置文件,比如:webapp目錄的設(shè)置、數(shù)據(jù)庫連接的設(shè)置、模板目錄的設(shè)置等 urls.py ###當(dāng)前項(xiàng)目url導(dǎo)航的設(shè)置,用一個(gè)正則匹配模式這匹配url規(guī)則并映射到指定的文件去處理請(qǐng)求
5、安裝django自帶的admin應(yīng)用,即安裝一個(gè)webapp
修改setting.py文件中的如下內(nèi)容:
DATABASES = { 'default': { 'ENGINE': 'sqlite3', #設(shè)置使用sqlite3數(shù)據(jù)庫 'NAME': r'C:Users。。。。 est.db', # sqlite3的文件路徑 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # 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. } } INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Uncomment the next line to enable the admin: 'django.contrib.admin', ##取消原來的注釋 # Uncomment the next line to enable admin documentation: 'django.contrib.admindocs', ##取消原來的注釋 )
修改urls.py問件中的如下內(nèi)容:
# Uncomment the next two lines to enable the admin: from django.contrib import admin ##取消注釋 admin.autodiscover() ##取消注釋 # 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)), ###取消注釋
6、同步admin應(yīng)用的數(shù)據(jù)庫:
在項(xiàng)目主目錄下使用命令:
manage.py syncdb
會(huì)提示創(chuàng)建一個(gè)超級(jí)用戶,輸入yes并按照提示創(chuàng)建一個(gè)賬號(hào)即可
7、測(cè)試admin應(yīng)用:
使用命令啟動(dòng)django的服務(wù):
manage.py runserver
瀏覽器中輸入地址:http://127.0.0.1:8000/admin/
如果出現(xiàn)登錄界面則說明admin應(yīng)用安裝成功,使用第6步中創(chuàng)建的賬號(hào)登錄即可
8、安裝admin的文檔模塊:
命令行輸入:
pip install docutils
安裝完成后重啟django服務(wù),訪問地址http://127.0.0.1:8000/admin/doc/
9、使用和學(xué)習(xí)admin應(yīng)用:
這個(gè)應(yīng)用主要用于管理項(xiàng)目的應(yīng)用的,同樣可以很方面的管理數(shù)據(jù)庫內(nèi)容,如果想自己的項(xiàng)目也能在這里被管理則需要進(jìn)行一個(gè)配置即可,后面將會(huì)有相關(guān)操作
默認(rèn)其功能有:管理admin應(yīng)用的用戶、用戶組;添加站點(diǎn)
10、創(chuàng)建自己的應(yīng)用:
項(xiàng)目主目錄下使用命令:
manage.py startapp myapp
命令會(huì)在當(dāng)前目錄下創(chuàng)建一個(gè)app的目錄mysite,其下有文件:
__init__.py models.py ##用于創(chuàng)建數(shù)據(jù)模型的,即設(shè)計(jì)數(shù)據(jù)庫結(jié)構(gòu)的,在這里面配置到數(shù)據(jù)庫的模塊,django會(huì)自動(dòng)幫你創(chuàng)建相應(yīng)的數(shù)據(jù)庫表結(jié)構(gòu) views.py ##視圖文件,用于響應(yīng)用戶請(qǐng)求并在處理后返回結(jié)果,這里面主要編寫請(qǐng)求事件的響應(yīng)函數(shù)
11、安裝自己的應(yīng)用:
和安裝admin應(yīng)用一樣,修改settings.py文件
INSTALLED_APPS = ( ...... 'djangoproject1.myapp', ###添加這一句 )
12、創(chuàng)建第一個(gè)頁面:
修改mysite目錄下的views.py文件,內(nèi)容如下:
from django.http import HttpResponse def home(request): return HttpResponse("Hello Django")
13、設(shè)置url請(qǐng)求頁面:
修改urls.py內(nèi)容如下:
urlpatterns = patterns('', # Examples: url(r'^$', 'djangoproject1.myapp.views.home', name='home'), )
14、測(cè)試自己的應(yīng)用:
重啟django服務(wù),
manage.py runserver
訪問:http://127.0.0.1:8000
如果出現(xiàn):hello django 則說明設(shè)置成功
第一個(gè)app實(shí)現(xiàn)
在環(huán)境搭建好了的基礎(chǔ)上我們還要繼續(xù)做的就是往里面填內(nèi)容了。也就是網(wǎng)頁的實(shí)際內(nèi)容,比如:頁面內(nèi)容,比如數(shù)據(jù)庫內(nèi)容,比如模塊內(nèi)容,比如css,js內(nèi)容等,那么在django中是怎么整合這些的,在這里記錄一下。
1、創(chuàng)建一個(gè)模式:
模式其實(shí)就是整個(gè)網(wǎng)站的數(shù)據(jù)模型,也就是數(shù)據(jù)庫的結(jié)構(gòu),即數(shù)據(jù)表結(jié)構(gòu),所以創(chuàng)建一個(gè)模式就是設(shè)計(jì)一張數(shù)據(jù)表,只不過在django的模式里用代碼形式來表示模式,然后它會(huì)幫助你自動(dòng)生成響應(yīng)的數(shù)據(jù)表及對(duì)應(yīng)的關(guān)系,而且對(duì)支持的數(shù)據(jù)庫都是統(tǒng)一的表示形式,即兼容性不錯(cuò),是不是很方便啊!樣例見下:
編寫app目錄中的models.py文件
from django.db import models class Location(models.Model): city = models.CharField(max_length=50) state = models.CharField(max_length=50, null=True, blank=True) country = models.CharField(max_length=50) def __str__(self): if self.state: return "%s, %s, %s" % (self.city, self.state, self.country) else: return "%s, %s" % (self.city, self.country) class Job(models.Model): pub_date = models.DateField() job_title = models.CharField(max_length=50) job_description = models.TextField() location = models.ForeignKey(Location) def __str__(self): return "%s (%s)" % (self.job_title, self.location)
2、讓模式生效:
在模式設(shè)計(jì)好了后就可以使用它,讓它幫你干活啦,查看模式創(chuàng)建的表是否正確的命令為:manage.py sql app_dir, 這樣可以查看表結(jié)構(gòu)的原型了。在檢查完表結(jié)構(gòu)原型后就應(yīng)用之,命令為:manage.py syncdb, 這個(gè)其實(shí)就是真正的在數(shù)據(jù)庫中建表。
3、如何應(yīng)用模式:
模式依然生效后就是如何去應(yīng)用它,也就是獲取其中的數(shù)據(jù)為我們服務(wù);在views.py文件中包括如下代碼即可調(diào)用具體的數(shù)據(jù)表;
from django.template import Context, loader from django.http import HttpResponse from myapp.models import Job def home(request): object_list = Job.objects.order_by('-pub_date')[:10] str_count = "The Count of job table is %s"%Job.objects.count() str_job_desc = "<br>".str(join(Job.objects.all())) return HttpResponse(str_count + "<br>" + str_job_desc)
重啟django,訪問http://127.0.0.1:8000,如果出現(xiàn)字符信息說明正確,只是這時(shí)顯示的是數(shù)據(jù)數(shù)據(jù)總數(shù)為0,內(nèi)容為空而已
4、在admin中配置我的應(yīng)用:
上面的內(nèi)容沒有數(shù)據(jù),那么就造一些數(shù)據(jù):一種是自己寫sql去造;不過還有一種方法就是在admin應(yīng)用中去造數(shù)據(jù),當(dāng)然首先是配置admin來管理我創(chuàng)建的應(yīng)用。在我的應(yīng)用目錄中新建一個(gè)admin.py文件,其內(nèi)容如下:
from django.contrib import admin from mydjango.myapp import models class DocumentAdmin(admin.ModelAdmin): pass class CommentAdmin(admin.ModelAdmin): pass admin.site.register(models.Location, DocumentAdmin) admin.site.register(models.Job, CommentAdmin)
重啟django,訪問http://127.0.0.1:8000/admin, 就可以看到我的應(yīng)用中的數(shù)據(jù)可以在這里管理了。
5、在admin中管理我的應(yīng)用:
在admin中設(shè)置好我的應(yīng)用后,就可以通過admin來為我的應(yīng)用添加數(shù)據(jù)了。具體就是點(diǎn)擊添加、輸入內(nèi)容、保存即可。等有了數(shù)據(jù)后我們?cè)诨氐街黜摽纯词遣皇琼撁鎯?nèi)容就由內(nèi)容了?
6、開始設(shè)置模板:
內(nèi)容少的時(shí)候我們可以每個(gè)頁面都自己寫,但是當(dāng)頁面變多,而且還有很多相同部分時(shí),我們就希望能不要寫那些同樣的東西了,那么模板就是為了解決這樣的問題而出現(xiàn)的,在django中配置模板的方法是在項(xiàng)目主目錄的settings.py文件中修改如下內(nèi)容:
TEMPLATE_DIRS = ( "C:/Users/xiaowu/workspace/mydjango/templates", ##注意斜線的格式,是/而不是,即使在windows下 )
7、創(chuàng)建模板文件:
在settings.py文件設(shè)置的模板目錄下新建模板文件,模板文件其實(shí)都是html文件,只是其中的內(nèi)容包含一些特殊的占位符,在實(shí)際應(yīng)用中會(huì)替換掉其中的內(nèi)容;這些內(nèi)容就是在代碼里實(shí)現(xiàn)出來的數(shù)據(jù)了;而且模板還可以繼承,這個(gè)也比較好用,就好像程序的代碼塊一樣分的越細(xì)可重用性就越好。樣例如下:
template主目錄下的base.html文件內(nèi)容
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Company Site: {% block title %}Page{% endblock %}</title> {% block extrahead %}{% endblock %} </head> <body> {% block content %}{% endblock %} </body> </html> template/mytemp目錄下的base.html內(nèi)容 [html] view plain copy {% extends "base.html" %} {% block extrahead %} <style> body { font-style: arial; } h1 { text-align: center; } .job .title { font-size: 120%; font-weight: bold; } .job .posted { font-style: italic; } </style> {% endblock %}
template/mytemp目錄下的job_list.html
{% extends "jobs/base.html" %} {% block title %}Job List{% endblock %} {% block content %} <h1>Job List</h1> <ul> {% for job in object_list %} <li><a href="{{ job.id }}">{{ job.job_title }}</a></li> {% endfor %} </ul> {% endblock %}
{% extends "mytemp/base.html" %} {% block title %}Job Detail{% endblock %} {% block content %} <h1>Job Detail</h1> <div class="job"> <div class="title"> {{ job.job_title }} - {{ job.location }} </div> <div class="posted"> Posted: {{ job.pub_date|date:"d-M-Y" }} </div> <div class="description"> {{ job.job_description }} </div> </div> {% endblock %}
在django中是在views.py中具體的引用模板,具體方法見下:
方法一:
from django.template import Context, loader from django.http import HttpResponse from myapp.models import Job def home(request): object_list = Job.objects.order_by('-pub_date')[:10] t = loader.get_template('mytemp/job_list.html') c = Context({ 'object_list': object_list, }) return HttpResponse(t.render(c))
方法二:
from django.shortcuts import get_object_or_404, render_to_response from myapp.models import Job def home(request,job_id): job = get_object_or_404(Job, pk=job_id) return render_to_response('mytemp/job_detail.html', {'object': job})
9、最后的views.py文件內(nèi)容如下:
from django.template import Context, loader from django.http import HttpResponse from myapp.models import Job from django.shortcuts import get_object_or_404, render_to_response def home(request): return HttpResponse("Hello Django") def index(request): object_list = Job.objects.order_by('-pub_date')[:10] t = loader.get_template('mytemp/job_list.html') c = Context({ 'object_list': object_list, }) return HttpResponse(t.render(c)) def detail(request,job_id): job = get_object_or_404(Job, pk=job_id) return render_to_response('mytemp/job_detail.html', {'object': job})
9、配置index、detail視圖的url,在urls.py添加如下內(nèi)容:
url(r'^job/$', ('mydjango.myapp.views.index')), url(r'^job/(?P<job_id>d+)/$',('mydjango.myapp.views.detail')),
然后重啟服務(wù)后,訪問http://127.0.0.1:8000/job/
ok,所有的結(jié)構(gòu)都已經(jīng)用到了,剩下的就是想出一個(gè)有趣的項(xiàng)目趕緊上手吧!