day 1
安裝django
sudo pip install django
創(chuàng)建一個項(xiàng)目
django-admin.py startproject myProject
啟動服務(wù)器
python manage.py runserver 8000
創(chuàng)建一個app
python manage.py startapp app1
day2
同步數(shù)據(jù)庫
python manage.py syncdb
以root用戶登錄mysql
mysql -u root -p
在mysql中創(chuàng)建Django 項(xiàng)目的數(shù)據(jù)庫
create database jangodb default charset=utf8;
在mysql中為Django 項(xiàng)目創(chuàng)建獨(dú)立用戶 并授予相關(guān)權(quán)限
grant select, insert, update, delete, create, drop , index, alter, create temporary tables, lock tables on jangodb.* to 'user'@'localhost' identified by 'password';
在setting.py中配置數(shù)據(jù)庫賬號信息
<code>
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'jangodb',
'USER': 'user',
'PASSWORD': 'password',
'HOST':'localhost',
'PORT':'3306',
}
}
</code>
day3
配置模版搜索路徑
打開settings.py
將系統(tǒng)默認(rèn)模版注釋掉 新加入
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, '模版路徑'), //相對于根目錄
)
使用模版 在views.py 中
from django.shortcuts import render
def templay(request):
context = {}
context['label'] = 'Hello World!'
return render(request, 'templay.html', context)
//以上代碼 會去找模版路徑下的templay.html文件 并將label 變量替換為 Hello World!
常用的模版標(biāo)簽
被 {{}} 包圍的是變量 ,被{%%}包圍的是塊標(biāo)簽
塊標(biāo)簽里邊可以包含 for 或 if else 語句
eg.
{% for item in item_list %}
{{item}}
{% endfor %}
{% if %}
{% elseif %}
{% endif %}
模版的繼承
{% extend 父級模版 %}
day4
get 和 post
獲取到request 后 可以 通過 GET 或 POST獲取數(shù)據(jù)
get :
<code>def investigate(request):
rlt = request.GET['staff']
return HttpResponse(rlt)</code>
post:
<code>def investigate(request):
ctx ={}
ctx.update(csrf(request))
if request.POST:
ctx['rlt'] = request.POST['staff']
return render(request, "investigate.html", ctx)</code>
將收到的數(shù)據(jù)存儲到數(shù)據(jù)庫
<code>submitted = request.POST['staff']
new_record = Character(name = submitted)
new_record.save()</code>
day5
django 提供了一個默認(rèn)的可以管理數(shù)據(jù)庫的app (django.contrib.admin)
在myside/setting.py 中的Installed_apps可以找到
訪問127.0.0.1:8000/admin 可以訪問到這個界面
用戶名密碼 可以通過
<code>python mange.py createsuperuser </code>
來創(chuàng)建一個超級用戶登錄進(jìn)去來管理數(shù)據(jù)
為了讓admin 來管理這個界面 需要將模型注冊到admin
在admin.py 中導(dǎo)入 模型類
<code>from site.models import model1</code>
將模型數(shù)據(jù)注冊到admin
<code>admin.site.register(model1)</code>
如果有多個模型 可以這樣寫
<code>admin.site.register([model1,model2])</code>
自定義界面
比如對某個屬性a 進(jìn)行管理 可以造一個aAdmin 類 并將他們一起注冊
<code>class aAdmin:(admin.ModelAdmin):
fields = ('property1', 'property2')
admin.site.register(a, aAdmin)
</code>
搜索
在aAdmin 類中加入一句
<code>search_fields = ('name's)</code>
day6
continue