版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領
文檔簡介
[Sun,20SepDjango基礎[Sun,20SepDjango[Sun,20SepDjango[Sun,20SepDjango[Sun,20SepDjango[Sun,20SepDjango[Sun,20Sep12:27]Django模板(temtes[Sun,20Sep12:27]Django[Sun,20Sep12:27]Django模型(數(shù)據(jù)庫)[Sun,20Sep12:27]Django?定義Field[Sun,20Sep12:27]DjangoQuerySetAPI[Sun,20Sep12:27]Django[Sun,20SepDjango[Sun,20SepDjango[Sun,20SepDjango[Sun,20SepDjango(Apache)[Sun,20Sep12:27]Django部署(nginx)[Sun,20Sep12:27]Django數(shù)據(jù)導?[Sun,20Sep12:27]Django[Sun,20SepDjango[Sun,20Sep12:27]Django?戶系統(tǒng)[Sun,20Sep12:27]Django[Sun,20Sep12:27]Django[Sun,20SepDjango[Sun,20SepDjango[Sun,20SepDjangosession[Sun,20SepDjangoAjax[Sun,20SepDjangoAjaxCSRF[Sun,20SepDjangoSitemap[Sun,20SepDjango[Sun,20SepDjango[Sun,20SepDjango[Sun,20Sep [Sun,20SepDjango[Sun,20Sep[Sun,20Sep其它(書寫中)[Sun,20SepDjangoCMS[Sun,20SepPython/Django[Sun,20Sep|下?項|章節(jié)菜單|主菜單
Django是由Python開發(fā)的?個免了,現(xiàn)在也?直在堅持寫,每?篇都可能Django英?的官?? 時候是Django的版本是1.6,Django的更新很快,?強學堂的也隨著更新了,兼顧了后來的新版本,從Django1.5到的?強學堂就是?Django搭建的站點!本作者:涂偉忠( 同意,禁?!)?強學堂學習的?篇?章:Django學習資源,如果有更好的也可以在?章下推問題):Django開發(fā)常?問題及答案匯總HTML,CSSJavaScript可以學會,Django很簡單!DjangoThisarticlewasdownloadedbycalibre |章節(jié)菜單|主菜單|下?項|章節(jié)菜單|主菜單|上?項Django并且使你的web開發(fā)充滿樂趣。通過DjangoDjango中提供了開發(fā)?站經(jīng)常?到的模塊,碼,Django使你能夠專注于web應?上有Django提供了通?Web開發(fā)模式的?度抽約定。Django的理念是DRY(Don'tRepeat 個,當然?不到數(shù)據(jù)庫的時候你可以不使?。views.py中的函數(shù)渲染temtes中的Html。Django的設置,配置?件,?如DEBUG的Thisarticlewasdownloadedbycalibre |章節(jié)菜單|主菜單|下?項|章節(jié)菜單|主菜單|上?項都試?次,建議??安裝bpython,這樣在ubuntusudoapt-getinstallpython-django-Fedora下安裝?yuminstallpython-?pipsudoapt-getinstallpython-yuminstallpython-Linux,MacOSXWindowsget-pip.py 運?pythonget-pip.py就可以安裝Note:也可以pip源碼包,運pip安裝(sudo)pipinstall或者(sudo)pipinstallDjango==1.6.10Windows如果提示‘python’不是內部或外部命令,也那說明你的Python沒有安裝好,或者環(huán)境Python2.7.9,pip,安裝三.源碼安 /downloLinuxMactar-xvzfdjango-1.7.6.tar.gzcddjango-1.7.6(sudo)pythonsetup.py輸?cmd,Win8在開始那?點右鍵,選擇命D:\django-1.7.6\cdcddjango-pythonsetup.py‘python’不是內部或外部命令,Python沒有安裝好,或者路徑?jīng)]有配置正確,參?:Python環(huán)境搭建pythonEnter,進?python環(huán)境>>>import>>>django.VERSION7,6,'final',>>>django.get_version()Django1.5,Django1.8virtualenvPython三? Thisarticlewasdownloadedbycalibre |章節(jié)菜單|主菜單|下?項|章節(jié)菜單|主菜單|上?項pythonmanage.pystartappapp-或django-admin.pystartappapp-pythonmanage.py注意:Django1.7.1及以上的版本需要?以下命令pythonmanage.pymakemigrationspythonmanage.py備注:對已有的models進?修改,Django結構的,不過有第三??具south,詳?Djangopythonmanage.py當提示端?被占?的時候,可以?其它端?:pythonmanage.pyrunserver8001pythonmanage.pyrunserver9999 所有可?pythonmanage.pyrunserver#對應的ip加端?,?pythonmanage.py此命令會詢問是yes還是no選擇yes會把pythonmanage.pypythonmanage.pydumpdataappname>appnamepythonmanage.pyloaddataappname.jsonpythonmanage.pybpythonipython會?動?它們的界?,強烈推薦?bpythonpythonmanage.pyDjango會?動進?在settings.py中設置的數(shù)據(jù)庫,如果是MySQL或postgreSQL,會要求輸?數(shù)據(jù)庫?戶。終端上輸?pythonmanage.py看: Thisarticlewasdownloadedbycalibre |章節(jié)菜單|主菜單|下?項|章節(jié)菜單|主菜單|上?項Django中?址是寫在urls.py?件中,?正則表達式對應views.py中的?個函數(shù)(或者(projectdjango-adminstartprojectdjango-adminpip安裝的,也是? ├──└── init├──├──└──?錄mysite中是?些項?的設置settings.py?件,總的urls配置?件urls.pywsgi.py mysite?錄下(不是mysitepythonmanage.pystartapplearnlearn我們可以看到mysitelearn?件 init├──├──├──└──修改INSTALLED_APPS=)備注,這?步是?什么呢?新建的app如果不加到INSTALL_APPS中的話,django就不 (app-name/static/中的?件),后?你會學fromdjango.httpimportdefreturnHttpResponse(u"歡迎光臨?強學堂第??是編碼為utf-8?到了中?,如果不就報錯返回內容的,就像Python中的print?樣,只不過HttpResponse是把內容顯示到??fromdjango.conf.urlsimportpatterns,fromdjango.contribimportadminurlpatterns=patterns('',#Examples:url(r'^$','learn.views.index',name='h#url(r'^blog/',)在終端上運?pythonmanage.pyrunserver我們會看到類似下?的信息:$pythonmanage.pyrunserverValidatingmodels...0errorsMay24,2014-Djangoversion1.6.5,usingsettingsStartingdevelopmentserveratQuittheserverwithCONTROL-C.pythonmanage.pyip:port的形式,?如pythonmanage.pyrunserver機器上所有ip8000端?,時?電腦的ip代替問Thisarticlewasdownloadedbycalibre |章節(jié)菜單|主菜單|下?項|章節(jié)菜單|主菜單|上?項 zqxtdjango-admin.pystartprojectzqxt_viewscdzqxt_viewspythonmanage.pystartapp││├──│├── ├── └──├──└── init├──├──└──fromdjango.shortcutsimportrenderfromdjango.httpimportHttpResponsedefa=b=c=return接著修改zqxt_views/urls.py?件,添fromdjango.conf.urlsimportpatterns,fromdjango.contribimportadminurlpatterns=patterns('',#Examples:url(r'^add/$','calc.views.add',name='#url(r'^blog/',)pythonmanage.py如果提示ErrorThatportisalreadyinuse.pythonmanage.pyrunserver8001址:就可?9,試著改變?下前?介紹的時候就Django?持優(yōu)雅的?calc/views.py?件,再新定義?個add2函數(shù),原有部分不再貼出defc=int(a)+return接著修改zqxt_views/urls.py?件,再添加?個新的url我們可以看到?址中多了(\d+),正則表達式中\(zhòng)d代表?個數(shù)字,+代表?個或多個前?的字符,寫在?起\d+就是?個或多個(知識請參?Python正則表達式),每?個?組都作為?個參數(shù)被views.py中 ?、urlfromdjango.conf.urlsimportpatterns,fromdjango.contribimportadminurlpatterns=#url(r'^add/$','calc.views.add',name='url(r'^add/(\d+)/(\d+)/$','calc.views.#url(r'^blog/',include('blog.urls')),)url(r'^add/$','calc.views.add',name='add'name='add是?想改成/4_add_5/這樣的格式,但是我們在我們在終端上輸?(推薦安裝bpython,這樣Django會?bpython的s pythonmanage.pyreverse接收url中的name作為第?個參數(shù)reverse來url的name不改,就不?改代碼中的?址。{%url'name'url'name參數(shù)<ahref="{%url'add2'45<a這樣就可以通過urladd24當urls.py進?更改,前提是不改name(這個這時url'add2'45就會渲染對應的?址成/new_add/4/5/,reverse函需要改urls.py中的正則表達式(url參Thisarticlewasdownloadedbycalibre |章節(jié)菜單|主菜單|下?項|章節(jié)菜單|主菜單|上?項Djangodjango.http.HttpResponse來把內容顯本節(jié)代碼是基于Django1.8,但Djangozqxt_tmpl項?,和?個名稱為django-admin.pystartprojectzqxt_tmplcdzqxt_tmplpythonmanage.pystartapp把learnINSTALLED_APPS=)fromdjango.shortcutsimportdefreturnrender(request,在learn?錄下新建?個temtes?件夾,??新建?個home.html├── init ├── ├── init ├── ├──tem └── ├── └──├──└── init├──├──└──4directories,12<!DOCTYPEfromdjango.conf.urlsimportinclude,urlfromdjango.contribimportadminurlpatterns=url(r'^$','learn.views.home',name='ho#url(r'^blog/',]pythonmanage.pypythonmanage.py zqxt通?的部分,?如導航,底部,統(tǒng)計代碼可以寫?個base.html<!DOCTYPE<title>blocktitle默認標題{%include'nav.html'{%blockcontent{%endblock{%include'bottom.html'{%include'#html'如果需要,寫?夠多的block以便繼承的模base.html就好了,繼承后的模板也可以在block塊中include其它的模板?home.html,繼承或者說擴展(extends)base.html,可以簡單{%extends'base.html'blocktitle歡迎光臨??endblock{%blockcontent{%include'ad.html'{%endblockindex.html,當我們在views.py中使?的時候,如何判斷是當前app的home.html呢?這就需要把每個app中的tem tes?件夾中再建?個app的名稱,僅和該app相關的模板放在app/temtes/app/?錄下zqxtapp,分別為tutorial和tryit├── init ├── ├── ├──tem └── ├── └── ├── └──├── init ├── ├── ├──tem └── ├── └── ├── └──├──└── init├──├──└──"tutorial/index.html"和等使?請看Django模板進階。Thisarticlewasdownloadedbycalibre |章節(jié)菜單|主菜單|下?項|章節(jié)菜單|主菜單|上?項Django模板中的循環(huán),條件判斷是?機,還是電腦,給出不?過濾器:管道符號后?的功能,?如{{var|length,求變量?度的#-*-coding:utf-8-fromdjango.shortcutsimportdefstringu"我在?強學堂學習Django,?它來建returnrender(request'home.html'{{stringforList內容defTutorialList=["HTML","CSS","jQuery"returnrender(request,'home.html',{'T{%foriinTutorialList{{i{%endfor?{% definfo_dict{'siteu'?強學堂contereturnrender(request'home.html'站點:info_dict.site內容:?不是Pythoninfo_dict['site'],效果如{%forkey,valueininfo_dict.items{{key}}:{{value{%endfor for循環(huán)的defListmap(strrange(100)?個?度為1returnrender(request'home.html'{'L{%foriteminList{{item{%endfor?變量forloop.last{%foriteminList{{item}}{%ifnotforloop.last%},{%{%endfor 1 0forloop.revcounter for
for循環(huán)的forloopfor{%forathleteinathlete_list<li>{{{%empty{%endforurl"view-name"arg1arg2%}#urlpatterns=patterns('',url(r'^add/(\d+)/(\d+)/$','calc.views.)#temte{%url'add'45址,假如我們以后修改urls.py中的的時候,?址會?動變成/jiafa/4/5/還可以使?as語句將內容取別名(相當于定{%url'some-url-name'argarg2as<ahref="{{the_url}}">到:{{the_url ==,!=,>=,<=,>,<這些?較{%ifvar>=90{%{%{%
var>=80%}var>=70%}var>=60{%endifand,ornot,in,notin?假如我們判斷num是不是在0到100{%ifnum<=100andnum>=0{%else{%endif'ziqiangxuetang在不在?個列表變量List中:{%if'ziqiangxuetang'inList{%endif檔:Thisarticlewasdownloadedbycalibre |章節(jié)菜單|主菜單|下?項|章節(jié)菜單|主菜單|上?項list或者dict上通過ajax?法得到新的數(shù)據(jù)并顯示在??渲染?個list或dict和其它的??部分?起 importunicode_li fromdjango.shortcutsimportrenderdefList=['?強學堂','渲染Json到模板']returnrender(request'home.html'{'L<scripttype="text/javascript">varList={{List}};UncaughtSyntaxError:的值要?json.dumps()處理,2.在??上要加?個safe過濾器。#-*-coding:utf-8- importunicode_li importjsonfromdjango.shortcutsimportdefList?強學堂渲染Json到模板Dict{'site'?強學堂'author涂returnrender(request,'home.html',{'List':json.dumps(List),'Dict':json.dumps(Dict)home.htmljsvarList={{List|safevarDict={{Dict|safe<!DOCTYPE<title>歡迎光臨?強學堂!<script <divid="list學習<div<scriptvarList={{List|safeconsole.log(遍歷List?法1for(iinList){}console.log('遍歷List?法2')for(variList.length1i0;i?標右鍵,審核元素,選擇consoleconsole.log(同時遍歷索引和內容,使?varDict={{Dict|safe}};console.log("兩種字典的取值?式 console.log("遍歷字典 for(iinDict){}完整代碼: zqxtjson.zip(基于DjangoThisarticlewasdownloadedbycalibre |章節(jié)菜單|主菜單|下?項|章節(jié)菜單|主菜單|上?項關的代碼?般寫在models.py中,Django 3,MySQL,PostgreSQL等數(shù)據(jù)庫,只需要在settings.py中配置即可,不?本節(jié)的代碼:(Django1.6,Python2.7測django-admin.pystartprojectlearn_modelscdlearn_models#進?到該項?的?件夾django-admin.pystartapppeople新建?個補充:新建app也可以?manage.pystartapppeople,需要的出的?個命令,并不是指?個django- settings.pyINSTALLED_APPS中,也INSTALLED_APPS=)people/models.py?件,修改fromdjango.dbimport name=models.CharField(max_length=30)age=models.IntegerField() pythonmanage.pysyncdb進?manage.py注意:Django1.7pythonmanage.pypythonmanage.py $pythonmanage.py>>>frompeople.models <:我們?了?個.objects.get()?法查詢出來詢結果中顯示< 這?并沒有顯示出與WeizhongTu的相關信息如果?戶多了就?法知道查詢出來的到底是誰name和age等字段中不能 線,因為在DjangoQuerySetAPI中有特殊的,student_name也合法,但是 name不合法,try,class,字(importkeyword;fromdjango.dbimport name=models.CharField(max_length=30)age=models.IntegerField() unicode#在Python3中使?def str(self)return按CTRL+C退出當前的Pythons ,重復p= (name="WZ",age=23)p= p.age=23建時返回的是True,已經(jīng)存在時返回 .objects.all()[:10]切?操作, "abc #名稱為abc但是不區(qū)分??寫,可以找到ABC,Abc,aBC,這些都符合條件 #名稱中包含"abc"的? #名稱中包含"abc",且abc不區(qū)分?? #正則表達式查詢 .objects.exclude(namecont#排除包含WZ的對象 .objects.filter(namecontain#找出名稱含有abc,但是排除是23程:檔:Thisarticlewasdownloadedbycalibre |章節(jié)菜單|主菜單|下?項|章節(jié)菜單|主菜單|上?項Django的官?提供了很多的Field,但是有提供了?定義Field的?法:取的時候解壓縮,如果發(fā)現(xiàn)壓縮后更?,就?原?本直接:classCompressedTextField(models.TextField) modelFieldsforstoringtext =defto_python(self,value):ifnotvalue:returnreturnexceptException:returnvaluedefget_prep_value(self,value):ifnotvalue:returnreturnvalueexceptException:tmp=value.encode('utf-8')exceptException:returnvalueiflen(tmp)>len(value):returnvaluereturnPython的變量,get_prep_value?于們來??寫?個ListField:繼承?fromdjango.dbimportmodelsimportastclassListField(models.TextField): =models.SubfieldBasedescription="Storesapython init(self,*args,**kwargs):super(ListField,self).init(*ardefto_python(self,value):ifnotvalue:value=ifisinstance(value,list):returnvaluereturn defget_prep_value(self,value):ifvalueisNone:returnreturnunicode(value)#usestr(valdefvalue_to_string(self,obj):value=returnListField,像?帶的Field?樣使?:classArticle(models.Model):labels=ListField()>>>fromapp.modelsimport>>>d=>>>>>>d.labels=["Python",>>>d.labels["Python","Django"]pythonmanage.py >>>fromblog.modelsimport>>>a=>>>>>>['Django','custom>>><typea.contentu'我正在寫?篇關于?定義>>> Thisarticlewasdownloadedbycalibre |章節(jié)菜單|主菜單|下?項|章節(jié)菜單|主菜單|上?項DjangoQuerySet上?篇我們學習了Django模型,也學習了?些基本的創(chuàng)建與查詢。這?專?來講?下數(shù)據(jù)庫接?相關的接?(QuerySetAPI),當然您這個集合叫做QuerySet。fromdjango.dbimportclassname=models.CharField(max_length=100)tagline=models.TextField() unicode(self): onreturnclassname=models.CharField(max_length=50)=models.Field() unicode(self):#return
onclassblog=headline=models.CharField(max_length=body_text=models.TextField()pub_date=models.DateField()mod_date=authors=models.ManyToManyField(Authorments=models.IntegerField()n_backs=rating= unicode(self):#returnself.headline
on>>>fromblog.modelsimport>>>b=Blog(name='BeatlesBlog',>>>#?法1?法twz= ?法twz= #?法4,?先嘗試獲取,不存在就創(chuàng)建,可以防?重復#返回值(object,True/False)object,True/False),創(chuàng)建時返回True,已經(jīng)存在時返回False>>>fromblog.modelsimport>>>entry=>>>cheese_blog=>>>entry.blog=>>>.objects.all(.objects.all()[:10切?操作,獲取10.objects.get(name="WeizhongTu.objects.filter(name="abc")#等于Per.objects.filter(nameiexact="abc").objects.filter(name.objects.filter(name.objects.filter(nameregex="^abc").objects.filter(nameiregex="^abc")#filter是找出滿?條件的,當然也有排除符合某條件的.objects.exclude(name.objects.filter(namees=Entry.objects.all()foreines:Entry.objects.all或者es就是Entry中是否有對象,應該?Entry.objects.all().exists()QuerySet?持切??len(es)可以得到EntryEntry.objects.count()來查詢數(shù)list(es)QuerySet變成importquery=importquery=#qs=qs.query=#RestoreAuthor.objects.all().order_by('-name在Author.objects.filter(namecontains="WeizhAuthor.objects.filter(name#找出名稱含有abc,但是排除是23歲.objects.filter(name.objects.all()[:10切?操作,前10.objects.all().reverse()[:2.objects.all().reverse()[0]#使?order_by,在欄?名(columnname)前加?Author.objects.order_by('-id')[:20id?般的情況下,QuerySet中不會出來重復的,重復是很罕?的,但是當多張表進?qs1=Pathway.objects.filter(labelname='xqs2=Pathway.objects.filter(reactionnameqs3=Pathway.objects.filter(inputername=qs=qs1|qs2|qs=2015.04.09未完待續(xù)。。 /en/Thisarticlewasdownloadedbycalibre |章節(jié)菜單|主菜單|下?項|章節(jié)菜單|主菜單|上?項Django(本?是基于django 相關?件:每個app中的admin.py? 本節(jié)代碼:帳號tuzqxtblog的進?zqxt_admindjango-admin.pystartapp#coding:utf-fromdjango.dbimportclasstitlemodels.CharField(u'標題max_lcontent=models.TextField(u'內容')pub_date=models.DateTimeField(u'update_timemodels.DateTimeField(u'blog加?到settings.pyINSTALLED_APPS=)提示:INSTALLED_APPS是?個元組,每次加?新的app的時候,在后?都加?個逗號,進?包含有manage.pypythonmanage.pypythonmanage.pymakemigrationspythonmanage.pymigrateCreatingtabledjango_admin_logCreatingtableauth_permissionCreatingtableauth_group_permissionsCreatingtableauth_groupCreatingtableCreatingtableCreatingtableCreatingtabledjango_content_typeCreatingtabledjango_sessionYoujustinstalledDjango'sauthsystem,whichmeansyoudon'thaveanysuperusersdefined.Wouldyouliketocreateonenow?(yes/no):yesUsername(leaveblanktouse'tu'):tuInstallingcustomSQL...Installingindexes...Installed0object(s)from0blogadmin.py?件(如fromdjango.contribimportadminfrom.modelsimportArticle 提示:urls.pyadmin的已經(jīng)默認開?:pythonmanage.py如果提示8000端?已經(jīng)被占?,可以?python ,就可以看到Articles我們會發(fā)現(xiàn)所有的?章都是叫Articleobject,blog中的#coding:utf-fromdjango.dbimportclasstitlemodels.CharField(u'標題max_lcontent=models.TextField(u'內容')pub_date=models.DateTimeField(u'update_timemodels.DateTimeField(u' unicode(self在Python3return #coding:utf- import fromdjango.dbimportfromdjango.utils.encodingimport classtitlemodels.CharField('標題max_lecontent=models.TextField('內容')pub_date=models.DateTimeField('update_timemodels.DateTimeField(' str(self):returnself.title 的unicode_li ls可以讓python2.x也像python3那個處理unicode字符,以便有更fromdjango.contribimportadminfrom.modelsimportArticleclassArticleAdmin(admin.ModelAdmin):list_disy=('title','pub_date','upd y就是來配置要顯示的字段的,當 first_name=last_name=defreturnself.first_name+''+selfmy_property.short_description="Fullnfull_name= list_disy=('full_name',)們需要?第三?插件South,參?DjangoDjango1.7及以上?以下命令來同步數(shù)據(jù)庫pythonmanage.pymakemigrationspythonmanage.pymigrate搜索功能:search_fields=('title','content /en/dev/篩選功能:list_filter('status',這樣就可 /en/dev/序:有時候我們需要對djangoadminsite進?修檔:定制加載的列表,根據(jù)不同的?顯示不同的classMyModelAdmin(admin.ModelAdmin):defget_queryset(self,request):qs=super(MyModelAdmin,ifrequest.user.is_superuser:returnqsreturn list_disy=('name','age')search_fields=('name',)defget_search_results(self,request,qqueryset,use_distinct=super(Perssearch_term_as_int=int(searchqueryset|=self.model.objects.returnqueryset,queryset是默認的結果,search_term是在fromdjango.contribimportclassdefsave_model(self,request,obj,formobj.user=request.userfromdjango.contribimportclassdefsave_model(self,request,obj,formobj_original=self.model.objects.gobj.user=request.user有fromdjango.contribimportclassdefsave_model(self,requestobjformifchange:#更改的時候obj_originalself.model.objecelse:#新增的時候obj_original=obj.user=request.userfromdjango.contribimportclassArticleAdmin(admin.ModelAdmin):defdelete_model(self,request,obj):Givenamodelinstancedeleteitfr#handlesomethingThisarticlewasdownloadedbycalibre |章節(jié)菜單|主菜單|下?項|章節(jié)菜單|主菜單|上?項Django有時候我們需要臺?get或post?法提html表單的知識。第?節(jié):源碼ab之和的簡單應?,??<!DOCTYPE<formaction="/add/"a:<inputtype="text"name="a">b:<inputtype="text"name="b"><textarea>中的name屬性來傳遞fromdjango.httpimportHttpResponsefromdjango.shortcutsimportrenderdefreturnrender(request,defa=b=request.GET['b']a=int(a)b=return再將函數(shù)和?址對應上,就可以了,詳情當然如果我們?動將輸?之后的數(shù)據(jù)在views是很不?便,所以Django提供了更簡單易?的forms來解決驗證等這?系列的問題。Django源碼 新建?個zqxt_form2進?到zqxt_form2?件夾,新建?個toolsAPPpythonmanage.pystartapptoolsfromdjangoimportclassa=b=#coding:utf-fromdjango.shortcutsimportrenderfromdjango.httpimportHttpResponsefrom.formsimportdefifrequest.method'POST':form=AddForm(request.POST)#a=b=form.cleaned_data['b']returnHttpResponse(str(int(a)else:#當正常form=returnrender(request,'index.html',<form{%csrf_token{{formfromdjango.conf.urlsimportpatterns,fromdjango.contribimportadminurlpatternspatterns('',#注意下?這??url(r'^$','tools.views.index',name='h)這樣的,但是Django的forms提供了:以上,在forms.py中都很容易實現(xiàn)Djangoforms請看DjangoAjaxThisarticlewasdownloadedbycalibre |章節(jié)菜單|主菜單|下?項|章節(jié)菜單|主菜單|上?項Django運?django-admin.pystartprojectDjango1.6版本以后的settings.py?件中#Buildpathsinsidetheprojectlikethis:importosBASE_DIR= )得到?件所在的上?級,BASE_DIR即為項?所在?錄。#SECURITYWARNING:don'trunwithdebugtuDEBUG=True TE_DEBUG=DEBUG=True時,如果出現(xiàn)bug便于我們?bug的詳情,可能?些不懷好?的??ALLOWED_HOSTS= ALLOWED_HOSTS允許你設置哪些可DEBUG=False時,這個為必填項,如果不想輸?,可以?ALLOW_HOSTS=['*']來允許所有的。STATIC_URL=STATIC_ROOT=staticjquery.js,bootstrap.min.css等?件。?般來說我們只要把靜態(tài)?件放在APP中的static?錄下,部署時?pythonmanage.pycollectstatic就可以把靜態(tài)?件收集到STATIC_ROOT?錄,但是有時我們STATICFILES_DIRS=os.path.join(BASE_DIR,"common_static"))common_static/var/www/static/中MEDIA_URL=MEDIA_ROOT= Django靜態(tài)?件和Django部署,Django1.5-Django TE_DIRS=os.path.join(BASE_DIR,'temtes').repos.path.join(BASE_DIR,'temtes2').re#...) TES={ 'DIRS':'APP_DIRS':]這樣就可以把模板?件放在temtesThisarticlewasdownloadedbycalibre |章節(jié)菜單|主菜單|下?項|章節(jié)菜單|主菜單|上?項js,css圖?,的是Django1.4以后的版本應該都?持下?fromdjango.contrib.staticfiles.urlsurlpatterns+=檔:Django1.5Django1.8#Staticfiles(CSS,JavaScript,# /en/1.8/howSTATIC_URL=STATIC_ROOT=os.path.join(BASE_DIR,其它存放靜態(tài)?件的?件夾,??不能包含STATIC_STATICFILES_DIRS=(os.path.join(BASE_DIR,"common_static"))這個是默認設置,默認會找STATICFILES_DIRS中所STATICFILES_FINDERS=()靜態(tài)?件放在對應的app下的static?件夾中,當DEBUGTrue時,Django就能?dj18staticapp├── ├──init ├── ├── └──init ├── ├──static應?blog下的static 【zqxt.png ├── └──├──common_static#已經(jīng)添加到 │├── init ├── ├── └──└──當settings.py中的DEBUGTrue時,打開開發(fā)服務器pythonmanage.pyrunserver直接/static/zqxt.png就可settings.pyapp共?的靜態(tài)?件,?如jquery.js等STATICFILES_DIRS=)把jquery.js放在common_static/js/下,這樣就可以在/static/js/jquery.js 示 #staticfilesimportosfromdjango.conf.urls.staticimportstaticfromdjango.confimportsettingsifmedia_root=os.path.join(settings.BASEurlpatterns+=static('/media2/',documfromdjango.conf.urls.staticimporturlpatterns=url(r'^$','app.views.index',)+ pythonmanage.py態(tài)?件全部拷?到settings.py中設置的STATIC_ROOT?件夾中?apache2或nginxAlias/static/<Directory/path/to/static>Requireallgrantedlocation/mediaalias}location/staticalias}<VirtualHost Alias/favicon.ico/path/to/static/Alias/media//path/to/media/Alias/static//path/to/static/<DirectoryRequireall<Directory/path/to/static>RequireallWSGIScriptAlias/<Directory<FilesRequireall如果你?的是apache2.2替Requireallgranted賦予權限Orderallow,denyAllowfromall備注:(?apachectlv剛開始搞Django的時候其實我也?直在找,因為畢竟asp,php可以直接路徑中對應的<VirtualHost AliasMatch"(?i)^/(.+)\.ico$""/path/toAliasMatch"(?i)^/(.+)\.js$""/path/to/AliasMatch"(?i)^/(.+)\.css$""/path/toAliasMatch"(?i)^/(.+)\.jpg$""/path/toAliasMatch"(?i)^/(.+)\.jpeg$""/path/tAliasMatch"(?i)^/(.+)\.png$""/path/toAliasMatch"(?i)^/(.+)\.gif$""/path/toAliasMatch"(?i)^/(.+)\.xml$""/path/toAliasMatch"(?i)^/(.+)\.xsl$""/path/toAliasMatch"(?i)^/(.+)\.txt$""/path/toAliasMatch"(?i)^/(.+)\.zip$""/path/toAliasMatch"(?i)^/(.+)\.rar$""/path/to<Directory/path/to/project>RequireallgrantedWSGIScriptAlias/ErrorLog/path/to/project/error.logCustomLog/path/to/project/access.logcnginxDjangoThisarticlewasdownloadedbycalibre |章節(jié)菜單|主菜單|下?項|章節(jié)菜單|主菜單|上?項Django部署B(yǎng)AEJAESAEBAE,SAE,JAE, ?: sae(Forksmallcode同學的,沒有測試過,SAE有?定的免費份額)Django+nginx+apt-get可以先??LinuxMint,它?起來更簡單,和ubuntuapache2sudoapt-getinstallapache2libapache2-apachectl-Serverversion:Apache/2.4.6(ubuntu)Serverbuilt: Dec5201318:32:22Alias/media//home/tu/blog/media/Alias/static//home/tu/blog/static/<Directory/home/tu/blog/media>Requireallgranted<Directory/home/tu/blog/static>RequireallgrantedWSGIScriptAlias/<Directory<Fileswsgi.py>Requireallgranted RequireallOrderdeny,allowAllowfromallimportfromos.pathimportPROJECT_DIR=dirname(dirname(abspath(filimportsys#4sys.path.insert(0,PROJECT_DIR)#5fromdjango.core.wsgiimportget_wsgi_appliapplication=get_wsgi_application()3,4,5?為新加的內容,作?是讓想了解的??搜索,第7?如果?臺服務器有多個djangoproject時?定要修改成上?那 會??不正常(當然也可以使?mod_wsgidaemon模式,點擊這?查看)假如項?位置在/home/tu/zqxt(在zqxtmanage.py,zqxt是項?名稱)cdsudood-R644sudofindzqxt-typed- od755#Sincethereisnosanewaytogetthepar#settingsaredefinedviaenvironmentvari#/etc/init.d/apache2,/etc/logrotate.d/apaexportAPACHE_RUN_USER=www-dataexportAPACHE_RUN_GROUP=www-datamedia?件夾?般?來存放?戶上傳?件,static?般?來放???站的js,css,圖?#Staticfiles(CSS,JavaScript,# STATIC_URL=STATIC_ROOT=#uploadfolderMEDIA_URL='/media/'MEDIA_ROOT=www-data?戶的寫權限,下?的?法?較假如上傳?錄為zqxt/media/uploads?件夾,進?media?件夾,將uploads?戶組改cdmedia進?mediasudochgrp-Rwww-datauploads od-Rg+wuploads備注:這兩條命令,?直接?sudochownRwww-data:www-datauploads好,因為下 Attempttowriteareadonlydatabase,同sudochgrpwww-datablogsudoodg+wblogsudochgrpwww-data sudoodg+w
專?弄?個?件夾,?它來放 3數(shù)據(jù)庫,sudoa2ensitesitename或sudoa2ensitepythonmanage.pyDEBUG=sudoserviceapache2再?站來查看具體的出錯信息catsitename.conf>wsgi.py>settings.py>urls.py>views.py明?了上?的關系Djangoproject建?個wsgi.py?件,更改??對應的Thisarticlewasdownloadedbycalibre |章節(jié)菜單|主菜單|下?項|章節(jié)菜單|主菜單|上?項Django部署cdzqxt進?項?zqxt?錄pythonmanage.pynginx安裝nginxsudoapt-getinstallpython-devsudoyuminstallepel-sudoyuminstallpython-develsupervisor?個專??來管理進程的?具,我們?它來管理gunicorn/uwsgisudopipinstallCentOS下,如果不是?常懂SELinux和SELinux和iptables的問題 sudo sudoserviceiptables或者開放?些需要的端?,?如sudoiptables-AINPUT-ptcp-mtcp--sudosystemctlstop或者開放需要的端?sudofirewall-cmd--zone=public--add-sudofirewall-cmd--備注:由于我還沒有?版本的dnf來安裝包,有需求的同學?測,gunicornuwsgisudopipinstallgunicorn-w4-b:8001-w表示開啟多少個worker,-b表示要使?的ip和port,我們這??的是8001, 電腦的所有ip。--pythonpath指定依賴包路徑,多個的時安裝sudopipinstalluwsgiuwsgi--http:8001--chdir這樣就可以跑了,--home指定virtualenv路徑,如果沒有可以去掉。project.wsgi指project/wsgi.py?件probablyanotherinstanceofuWSGIisbind():Addressalreadyinuselsof-i這時根據(jù)PID可以?下?令kill掉相關sudokill-92208psaux|grepsupervisor默認配置?件,?如我們放在/etc/supervisord.conf路徑中:sudoecho_supervisord_conf>command=/path/to/uwsgi--http:8003--chdisupervisorsupervisord-czqxt程序(項?supervisorctl-c/etc/supervisord.confsupervisor管理的某個程序或所有程序:supervisorctl-c/etc/supervisord.conf以uwsgi為例,上?這樣使???命令太?了,我們使?ini配置?件來搞定,?如項?在/home/tu/zqxt這個位置,socket=/tmp/zqxt.sock注意上?的/tmp/zqxt.sock,?會?我們把它和nginx關聯(lián)起來。修改supervisorcommand=/path/to/uwsgi--ini/path/to/projsupervisorctl-c/etc/supervisord.conf或者supervisorctlcsudovim/etc/nginx/sites-upstreamzqxt_uwsgiserver}server location/mediaalias}location/staticalias}location/uwsgi_pass }}sudoln-s/etc/nginx/sites-nginxsudoservicenginx或者sudoservicenginx nginx與iptables:centosFireWalld:http:/ ubuntuufw uwsgiini配置?件:Thisarticlewasdownloadedbycalibre |章節(jié)菜單|主菜單|下?項|章節(jié)菜單|主菜單|上?項Django1.4,1.5也沒有問題,沒有提到的python從以前的blog上獲取過來的,想導? 本源代碼 建議先不要看源碼,按?步步做下去,遇到問題再試試源代碼,直接粘貼,很快就django-admin.pystartprojectmysitecdmysitepythonmanage.pystartappblogmodels.pyfromdjango.dbimportmodelsclassBlog(models.Model):title=content= unicode(self):returnself.titlepythonmanage.pyOperationstoSynchronizeunmigratedapps:Applyallmigrations:admin,contenttypesSynchronizingappswithoutmigrations:CreatingCreatingtableblog_blogInstallingcustomSQL...InstallingRunningApplyingcontenttypes.0001_initial...OKApplyingauth.0001_initial...OKApplyingadmin.0001_initial...OKApplyingsessions.0001_initial...OKYouhaveinstalledDjango'sauthsystem,anWouldyouliketocreateonenow?(yes/no):Username(leaveblanktouse'tu'):tuaddress:Password(again):Superusercreatedpythons如何進?對應?錄?看Django環(huán)境搭建的3.2部分$pythonmanage.py>>>fromblog.modelsimportcontent="IamBlog.objects.all(獲取所有blog[<Blog:Thefirstblogofmysite>]>>>blog2=>>>blog2.title="title>>>blog2.content="content>>>>>>blog2=Blog(title="title>>>的時候,要記得最后要保存?下blog.save(),1234567title8****contenttitle9****content?錄下寫?個,叫txt2db.py,把#!/usr/bin/envpythonimportosimportdjango否則會拋出錯誤importifdjango.VERSION1,7):#?動判斷版本deffromblog.modelsimportBlogf=open('oldblog.txt')forlineintitle,content=
=="mainpython運?完后顯示?個Done運?完畢后會打出?個"Done!數(shù)據(jù)已經(jīng)全導??;蛘吣阍俅芜\?上?令,你會發(fā)現(xiàn)django.db.models中還有?個函數(shù)叫返回值是(BlogObject,True/False)新建時返回True,已經(jīng)存在時返回False。檔:QuerySetAPImanage.pydumpdata導出的?件,示例如[{"model":"myapp. "pk":1,{"first_name":"John","last_name":}{"model":"myapp. "pk":2,{"first_name":"last_name":}?件,然后?pythonmanage.pyloaddatafixture.json導?詳?:可以寫?個,把要導?的數(shù)據(jù)轉化成#!/usr/bin/envpythonimportosdeffromblog.modelsimportBlogf=open('oldblog.txt')BlogList=[]forlineintitle,content=line.split('****')blog=Blog(title=title,content=con
=="main解析代替for循環(huán)會更快??!#!/usr/bin/envpythonimportosdeffromblog.modelsimportBlogf=open('oldblog.txt')BlogList=[]forlineinf:parts=line.split('****')以上四?也可以?列表解析#BlogList=[Blog(title=line.split('**
=="mainThisarticlewasdownloadedbycalibre |章節(jié)菜單|主菜單|下?項|章節(jié)菜單|主菜單|上?項models.py之后pythonmanage.pysyncdb只會將新類創(chuàng)建表,刪除的類詢問是段或者刪除字段只能參考pythonmanage.pysqlappname給出的SQL語句,然后???動到數(shù)據(jù)庫去?SQL語?操?south這個appDjango1.7及以后的版本集成了South的django項?提供了?個導出的?法pythonmanage.pydumpdata不指定appname時默認為導出所有的apppythonmanage.pydumpdata[appname]>?如我們有?個項?叫mysite,app叫blogblogpythonmanage.pydumpdatablog>pythonmanage.pyloaddatapythonmanage.pydumpdataauth>?Django?帶 跟不上了,想換成postgreSQL,或者MySQLpythonmanage.pydumpdata>pythonmanage.pyloaddata 動在了DjangoPostgreSQL導出數(shù)據(jù)庫zqxt到zqxt.sqlpg_dumpzqxt>導?數(shù)據(jù)庫到psqlzqxt-f?使????具,?如phpMyAdmin導?導導出數(shù)據(jù)庫zqxt到zqxt.sqlmysqldump-uusername-p--databasezqxt#mysql-uusername-輸?進?MySQL命令source這樣的話?pythonmanage.pydumpdata?法導出與的關系,但是數(shù)據(jù)庫整個去導出關系再導?。Djangopythonmanage.pydumpdata和pythonmanage.pyloaddata最?的好處就是可以pythonmanage.pypythonmanage.py常?的?具有:south,dmigrations,django-evolution推薦使?south,Django1.7中集成了southDjango的第三?appSouth就是專?做數(shù)據(jù)庫表結構?動遷移?作,JacobKa Moss曾做過?次 ,South名列最受歡迎的第三?app。事實上,它現(xiàn)在已經(jīng)儼然成為Django事實上的數(shù)據(jù)庫表遷移標準,很多第三?app都會帶Southmigrations 1,安裝(sudoapt-getinstallpython-django-south#或者利?pip安裝(sudo)pipinstallSouth或者?easy_installSouth來安裝,也可以源碼包,或者運?pythonsetup.pyinstall #ApplicationdefinitionINSTALLED_APPS=()修改好后運??次pythonmanage.pysyncdb,Django會新建?個pyt
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經(jīng)權益所有人同意不得將文件中的內容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
- 6. 下載文件中如有侵權或不適當內容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年度農(nóng)村房屋改造裝修環(huán)保材料采購與施工合同2篇
- 2025年度智慧城市建設中股東股權變更管理合同3篇
- 2025年度跨境電商倉儲租賃服務協(xié)議3篇
- 2025年度教育科技公司股權置換合同樣本3篇
- 2025年度汽車環(huán)保材料研發(fā)與應用合作合同3篇
- 二零二五年度納米材料研發(fā)委托合同2篇
- 二零二五年度智慧養(yǎng)老設施運營管理服務合同3篇
- 二零二五年度農(nóng)村土地置換與農(nóng)業(yè)人才培養(yǎng)合作協(xié)議2篇
- 2025年度公司高管聘用合同全新版:企業(yè)數(shù)字化轉型合作協(xié)議3篇
- 二零二五年度養(yǎng)殖場動物福利保障承包協(xié)議3篇
- 廣西北海市2023-2024學年八年級(上)期末數(shù)學試卷
- 非急救轉運合同范例
- 車輛使用安全培訓
- 《中國傳統(tǒng)文化》課件模板(六套)
- 民航客艙服務管理Ⅱ學習通超星期末考試答案章節(jié)答案2024年
- 兒科主任年終總結
- 期末 (試題) -2024-2025學年人教PEP版英語四年級上冊
- 第三單元 (單元測試)-2024-2025學年-四年級上冊語文統(tǒng)編版
- 浪潮銷售在線測評題
- 總經(jīng)理年會發(fā)言稿模板怎么寫(8篇素材參考)
- 《完善中國特色社會主義法治體系》課件
評論
0/150
提交評論