學(xué)會異常捕獲
當(dāng)程序出現(xiàn)問題時,學(xué)會使用異常捕獲靴拱,such as:查詢結(jié)果集中沒有想要的查的對象或字段垃喊,返回xxDoesNotExist,這時就可以捕獲這個異常,進(jìn)行下一步處理袜炕。
django靜態(tài)文件
1-1. 在settings.py文件中找到INSTALLED_APPS缔御,加入‘django.contrib.staticfiles’
1-2. 在TEMPLATE_CONTEXT_PROCESSORS中加入 'django.core.context_processors.static'
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'django.core.context_processors.static',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
)
1-3. setting.py中加入templates_url
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static/'),
# '/var/www/static',
)
- 在urls.py中加入
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
需要注意的是,上面代碼的第一行必須放在整個urls文件的第一行妇蛀,上面代碼的最后一行必須放在urls文件的最后一行耕突。
- 在templates中加入:
{% load staticfiles %}
小細(xì)節(jié)
在改變models.py的時候要重新生成sqlite3,不然可能更新不了
在django查詢結(jié)果集中可以用xx.order_by(’yy‘)按字段 ’yy‘ 排序
在django中评架,與前端ajax交互的時候眷茁,可以以文件流的形式返回一個參數(shù),django 在返回頁面是返會的都是Response對象纵诞,可以當(dāng)成文件流來操作
res = HttpResponse()
with open('static/html/resume_detail.html') as f:
res.write(f.read())
return res
在操作文件流時可以用with,作用范圍就在with下的函數(shù)塊內(nèi)上祈,當(dāng)然如果你記得close()也可以不用
with.....as ....:
xxxxx
- 在接收前端傳回的數(shù)據(jù)時注意檢查傳過來的數(shù)據(jù)類型
request.POST.getlist()#list ajax在傳數(shù)組的時候會在后面加’[]‘,接收的時候要在鍵的后面加’[]‘
request.POST.get()#json 要先用json.loads()轉(zhuǎn)換json對象
字符串轉(zhuǎn)換為字典:
>>> a = '{'a':1,'b':2}'
>>>type(a)
'unicode'
>>>d = eval(a)
{'a':1,'b':2}
>>>type(d)
'dict'