Python Django 学习笔记
最近在學(xué)校Python和Django。在學(xué)習(xí)中遇到了種種的問題,對(duì)于一個(gè)新手來說,下面的問題可能都會(huì)遇到。希望能幫助到那些和我一樣的人!!
0.python-dev安裝(ubuntu)
1.Open(filename,mode)
報(bào)錯(cuò)實(shí)例:?f = open('d:\Users\168935495Request.xml','r')
錯(cuò)誤信息"SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape"
解決方法:?f = open(r'd:\Users\168935495Request.xml','r')
原因:文件名中的 \U 開始的字符被編譯器認(rèn)為是八進(jìn)制
2.Module Path
python安裝目錄在C:\Python33,fibo.py文件在E:\Python。
報(bào)錯(cuò)實(shí)例:import fibo
錯(cuò)誤信息“ImportError: No module named 'fibo'”
解決方法:import sys
sys.path.append('E:\Python')
? import fibo
原因:需要在sys中配置工作目錄
2.5 不同目錄導(dǎo)入模塊
錯(cuò)誤信息“ImportError: No module named 'fibo'”
解決方法:在目錄下新建空文件__init__.py
3.Python2.7中文不識(shí)別
錯(cuò)誤信息“SyntaxError: Non-ASCII character '\xc9'”
解決方法:文件頭#coding=gbk
4.mysqldb 模塊安裝(目前只支持python 2.7)
系統(tǒng)32位的從https://pypi.python.org/pypi/MySQL-python/1.2.4下然后直接安裝
系統(tǒng)64位的從http://arquivos.victorjabur.com/python/modules/MySQL-python-1.2.3.win-amd64-py2.7.exe下然后直接安裝
5.import MySQLdb?
錯(cuò)誤信息:this is MySQLdb version (1,2,4,'beta',4),but _mysql is version (1,2,3,'final‘,0)
解決方法:刪除\Lib\site-packages下所有的mysqldb,重新安裝
6.格式化
整型數(shù):%d 無符號(hào)整型數(shù):%u 八進(jìn)制:%o 十六進(jìn)制:%x %X 浮點(diǎn)數(shù):%f科學(xué)記數(shù)法
字符串: %s?如果沒有什么特殊需求完全可以全部使用’%s‘來標(biāo)記
7.with用法
with conn:
????conn.execute("insert into sometable values (?,?)",("foo","bar"))
在這個(gè)例子中,commit()是在所有with數(shù)據(jù)塊中的語句執(zhí)行完畢并且沒有錯(cuò)誤之后自動(dòng)執(zhí)行的,如果出現(xiàn)任何的異常,將執(zhí)行rollback()操作,再次提示異常
8.文件每次修改后,需要重啟服務(wù)
9.python連接MySQL連接串(注意編碼)
python連接MySQL時(shí)加上編碼參數(shù)?conn = MySQLdb.Connection(host='localhost', user='root', passwd='123', db='test',charset='utf8')
9.5Django配置MySql
DATABASES = {
??? 'default': {
??????? 'ENGINE': 'django.db.backends.mysql', #Mysql引擎
??????? 'NAME': 'meiwei',????????????????????? # 數(shù)據(jù)庫(kù)名,不需要路徑以及后綴的??
??????? 'USER': 'root',#用戶
??????? 'PASSWORD': '',#密碼
??????? 'HOST': '',????????????????????? # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
??????? 'PORT': '',????????????????????? # Set to empty string for default.
??? }
}
10.Django模板錯(cuò)誤
錯(cuò)誤信息:Requested setting TEMPLATE_DEBUG, but settings are not configured. You must either define
解決方法:from?django.conf?import?settings ?
?settings.configure() ?
11.設(shè)置靜態(tài)資源路徑
settings.py
import os.path
TEMPLATE_DIRS = (
#靜態(tài)模塊文件存放路徑
os.path.join(os.path.dirname(__file__), 'templates').replace('\\','/'),
)
使用處
from django.template.loader import get_template
?t = get_template('shoplist.html')
12.model設(shè)置表名和主鍵自增(django 默認(rèn)的表是項(xiàng)目名+類名,主鍵是id)
from django.db import models
class Shop(models.Model):
??????? class Meta:
??????????? db_table='shops'#指定表名,忽略django自動(dòng)映射的表名(項(xiàng)目_class)
??????? ShopId? = models.AutoField(primary_key=True,db_column='sid')#指定列名
13.Templates模塊
需要和model對(duì)象的屬性一致(大小寫敏感)
?14.Model中的__unicode__(self)
請(qǐng)確保你的每一個(gè)模型里都包含 __unicode__() 方法,這不只是為了交互時(shí)方便,也是因?yàn)?Django會(huì)在其他一些地方用 __unicode__() 來顯示對(duì)象。
15.DateTimeField received a naive datetime (2013-08-19 18:44:32) while time zone support is active.
settings 修改 USE_TZ=False
參考:https://docs.djangoproject.com;http://www.djangobook.com
16.form自定義error,輸出message
class ShopForm(forms.Form): def clean(self): cleaned_data =self.cleaned_data data_shopname = cleaned_data.get('shopname') if data_shopname is None: raise forms.ValidationError(u'商戶名不能空') if len(data_shopname)>50: raise forms.ValidationError(u'商戶名長(zhǎng)度不能超過50') return cleaned_dataform = ShopForm(request.POST,error_class=ErrList) message= form.errors['__all__'].__unicode__()16.5使用Form驗(yàn)證表單數(shù)據(jù) (表單中的name名稱必須和form類中的名稱一致)
#form.pyclass ShopPicForm(forms.Form):shopname = forms.CharField(label="商戶名",error_messages={"required":u"商戶不可空"})picname = forms.CharField(label="圖片名",help_text="長(zhǎng)度范圍2-20",max_length=20,min_length=2,error_messages={"required":u"圖片名不可空","min_length":u"最小長(zhǎng)度2","max_length":u"最大長(zhǎng)度20"})picup = forms.ImageField(label="選擇圖片",error_messages={"required":u"圖片不可空"}) #view.py form = ShopPicForm(request.POST)if form.is_valid(): #do somethingelse:return render(request,"picadd.html",{"f":form}) #template 圖片名:<input type="text" name="picname" value="{{f.data.picname}}"/> {{f.errors.picname.as_text}}<br/> 商戶名:<input type="text" name ="shopname" autocomplete="on" value="{{f.data.shopname}}"/>{{f.errors.shopname.as_text}}<br/>
16.9修改errors鍵的值:
#.py from django.forms.util import ErrorList form.errors['username'] = ErrorList([u'帳號(hào)錯(cuò)誤']) #.html {{form.errors.username.as_text}}17.Template中使用cleaned_data
在view.py中使用 form.cleaned_data['鍵名'],template中使用form.cleaned_data.鍵名
?18.加載動(dòng)態(tài)下拉框(數(shù)據(jù)從數(shù)據(jù)庫(kù)查詢)
#form代碼def __init__(self, *args, **kwargs):super(ShopForm, self).__init__(*args, **kwargs) self.fields['cid'].choices = [('0','請(qǐng)選擇')]+\[(c.cid,c.categoryname) for c in CategoryModel.objects.all()]#另一種
CATEGORY_CHOICES = [('0','請(qǐng)選擇')]+[(c.cid,c.categoryname) for c in CategoryModel.objects.all()]
cid = forms.ChoiceField(choices=CATEGORY_CHOICES)
?19.下拉框設(shè)置選中
#view.py form.fields['cid'].choices = [(1,1),(2,2),(3,3)] form.fields['cid'].initial = [2]#選中第二個(gè)?20.圖片上傳
#modelurl = models.ImageField(upload_to = "%Y/%m/%d",blank=True)#注意此處頭部不要帶/,否則會(huì)提示Attempted access to '' denied. #formurl = forms.ImageField() #view?form = UploadFileForm(request.POST, request.FILES)必須要將request.FILES傳給form的構(gòu)造函數(shù),才能將文件數(shù)據(jù)綁定到form.if 'picup' in request.FILES:image = request.FILES["picup"]else:image =Nonename = request.POST["picname"]s = ShopPicModle(name=name,url=image)s.save() #template <form action="/pic/create/" method="post" enctype="multipart/form-data">圖片名:<input type="text" name="picname"/><br/>圖片:<input type="file" name="picup" /><br/><input type="submit" name="添加"/> {% csrf_token %} </form>?20.靜態(tài)資源(圖片)顯示
#url配置url(r'^images/(?P<path>.*)$','django.views.static.serve', {'document_root': "/path/to/your/images/"}),#/person/web/web/images/ #template <img src='/images/{{s.url}}' width="100px"/>DB中URL值:/shopspic/2013/08/29/ee244141a4874db7aeb034d3bd043306_550_412.jpg
圖片在磁盤上的路徑:person\web\web\images\shopspic\2013\08\29\ee244141a4874db7aeb034d3bd043306_550_412.jpg
21.生產(chǎn)環(huán)境關(guān)閉DEBUG,500的錯(cuò)誤
DEBUG = False,只是這樣會(huì)出現(xiàn)500的錯(cuò)誤,需要在ALLOWED_HOSTS = ['域名'或'ip'或'*']。生產(chǎn)環(huán)境推薦使用域名
22.MD5加密
from hashlib import md5
md5('加密字符串').hexdigest()
23.Cookie設(shè)置
#設(shè)置cookie response = render_to_response("login.html", {"message":message}) response.set_cookie(key,value="vv",path='/') return response #獲取cookie
? cookie = request.COOKIES.get(key)
24.模板繼承
?{%block%}告訴模板引擎。子模塊可以重載這部分。
#base.html <html><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><link type="text/css" rel="stylesheet" href="/static/css/base.css"/><title>{%block title %} {%endblock%}</title><body><h1>后臺(tái)管理</h1><p class="path">當(dāng)前位置:{%block path%}{%endblock%}<span>歡迎你:{{admin}} <a href="#">注銷</a></span></p>{%block content%}{%endblock%}</body> </html>#piclist.html {%extends "base.html"%} {%block title %}圖片列表頁面{%endblock%} {%block path%}圖片列表{%endblock%} {%block content%} 內(nèi)容 {%endblock%}25.自定義contextprocessor
a)修改settings
TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.request', 'django.contrib.auth.context_processors.auth', 'web.offline.cookie.logined', # 自定義的 context processors 函數(shù),格式:項(xiàng)目.包.模塊.方法 )b)logined方法
def logined(request):c = request.COOKIES.get(web.settings.COOKIENAME)if c:context = {'admin':c}else:context = {'admin':"未登錄"}return context #返回必須是字典26.配置多個(gè)數(shù)據(jù)庫(kù)
#settings.py DATABASES = {'default': {'ENGINE': 'django.db.backends.mysql', 'NAME': 'meishi', # database 'USER': '','PASSWORD': '','HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.'PORT': '', # Set to empty string for default. },'backup': {'ENGINE': 'django.db.backends.mysql','NAME': 'meishi2', 'USER': '','PASSWORD': '','HOST': '', 'PORT': '', # Set to empty string for default. } } #view.py Shop.objects.all().order_by('-ShopId')#默認(rèn)使用的是default Shop.objects.all().using('backup').order_by('-ShopId')#使用其他數(shù)據(jù)庫(kù)?27.Cookie設(shè)置后跳轉(zhuǎn)Url(這個(gè)問題糾結(jié)了很久)
response = HttpResponseRedirect('/piclist/')# response.set_cookie(web.settings.COOKIENAME,value=owner.name,path='/') return response?28.自定義404頁面
#urls.py handler404 = 'project.view.404' #需要把settings.py中的DEBUG=False才會(huì)生效?29.提交表單報(bào)錯(cuò):RuntimeError: You called this URL via POST,
????? but the URL doesn’t end in a slash and you have APPEND_SLASH set.
30.Url配置name參數(shù),
#urls.py url(r'^$', 'wetrip.views.home.index', name='home'), #template <a href="{%url 'home'%}">首頁</a> 以后url地址發(fā)生變化,只需要修改urls文件即可.?31.文件操作(需要目錄已存在)
#view.py 寫文件 file_handle = open(file_path,'w+') file_handle.write(data) #encode('utf8') file_handle.close() #讀文件 file_handle = open(file_path) data = file_handle.read() #decode('utf8') file_handle.close()?32.目錄創(chuàng)建
#多層創(chuàng)建目錄函數(shù)os.makedirs(path)。當(dāng)父目錄不存在的時(shí)候os.mkdir(path)不會(huì)創(chuàng)建,os.makedirs(path)則會(huì)創(chuàng)建父目錄。 def mkdir(path):# 引入模塊import os# 去除首位空格path=path.strip()# 去除尾部 \ 符號(hào)path=path.rstrip("\\")# 判斷路徑是否存在# 存在 True# 不存在 FalseisExists=os.path.exists(path)# 判斷結(jié)果if not isExists:# 如果不存在則創(chuàng)建目錄print path+' 創(chuàng)建成功'# 創(chuàng)建目錄操作函數(shù)os.makedirs(path)return Trueelse:# 如果目錄存在則不創(chuàng)建,并提示目錄已存在print path+' 目錄已存在'return False?33.返回403
1. 在settings.py里面的MIDDLEWARE_CLASSES中加入django.middleware.csrf.CsrfResponseMiddleware2. 在settings.py里面的MIDDLEWARE_CLASSES中去掉django.middleware.csrf.CsrfViewMiddleware?34.返回Josn格式數(shù)據(jù)
#view.py from django.utils import simplejsonjson={'ret':ret,'save_name':new_name} #支持中文 return HttpResponse(simplejson.dumps(json,ensure_ascii = False))?35.html轉(zhuǎn)義
#template {% autoescape off %} coding... {% endautoescape %} 這里的off 參數(shù)表明被autoescape包含的信息都不需要執(zhí)行HTML轉(zhuǎn)義。on 參數(shù)表示需要執(zhí)行HTML轉(zhuǎn)義?36.訪問遠(yuǎn)程圖片
import cStringIO, urllib2, Imageurl = 'remote picture' file = urllib2.urlopen(url) tmpIm = cStringIO.StringIO(file.read()) im = Image.open(tmpIm)?37.‘gbk' codec can't encode character 錯(cuò)誤
#忽略特殊字符 str.encode('gbk','ignore')?38.獲取Post name相同的值(如多個(gè)checkbox)
#view.py request.POST.getlist('name')?39.創(chuàng)建Django(path到django目錄下)
django-admin.py startproject mysite
40.中文輸出
u'中文'
41.模板注釋
{# 文字#}注釋的內(nèi)容不會(huì)在模板渲染時(shí)輸出。注釋不能跨多行
42.密碼框
password = forms.CharField(widget=forms.PasswordInput())43.Template中{{ 變量}} 不要換行
44.'ascii' codec can't encode characters in position 0-4: ordinal not in range(128) ?python版本2.7
在model中增加
def __unicode__(self):
? ? ? return self.question_text
?
未完待續(xù)...
轉(zhuǎn)載于:https://www.cnblogs.com/zhxhdean/p/3173663.html
總結(jié)
以上是生活随笔為你收集整理的Python Django 学习笔记的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 自定义Windows性能监视器
- 下一篇: 不作35岁的程序员?