本博文根據python2.7.3、Django1.7.1,運行環境爲linux Ubuntu12.04,當然開始學習django是在win7 python2.7.8 Django1.7下搭建,後來發現在linux下開發可以省去一些default設置的修改,就轉戰linux學習。該博文針對win7,這一篇開始將細講linux環境下開發
linux下django開發環境的搭建和windows下環境搭建類似,在命令下有一點出入,例如templates文件夾在win7下是得放在工程目錄下(不太記得了),而linux得放在app目錄下。二話不說,上圖比說的更有說服力。
1、目錄結構
mytest1爲project,hello爲app
django-admin startproject mytest1
django-admin startapp hello
2、部署完後可以開始啓動服務器了
當然可能會出現啓動不成功的情況,在win7下也可能有遇到過,執行如下操作即可
3、說說view.py中怎樣使用模板吧
①from django.template import loader,Context
......
t=loader.get_template(‘index.html’) # 等於 t=template.Template(‘str’)
c=Context({})
html=t.render(c)
return HttpResponse(html)
②from django.shortcuts import render_to_response
......
return render_to_response(‘gujiawei.html’,{})
在稍後的文章中會專門淺談利用模板與python交互的例子。
4、多對多映射小記
author.objects.create(name=’Alen’)
....
authors=Author.objects.all()
b1=Book()
b1.name=’python book1’
b1.save()
alen=Author.objects.get(name__exact=’Alen’)
b1.authors.add(alen) #add remove filter(name__exact=’Alen’)...
b1.authors.add(authors[1])
....
b1.authors.all()
...
alen.book_set.all() alen.book_set.add(b1)
alen.book_set.create(name=’python book2’) alen.book_set.remove()
5、表單方法
表單方法很有用,可以讓javascript中操作得到的數據利用表單上傳到服務器,進而操作數據庫
利用url默認爲get方法,submit提交後爲POST方法
點擊submit後會觸發post方法。(req.POST參數能在用戶輸入爲空的的時候反饋錯誤信息)
在稍後的文章中會專門細講利用表單成功操作數據庫(mongodb)的案例。