Python & Django 學習筆記

最近在學校Python和Django。在學習中遇到了種種的問題,對於一個新手來講,下面的問題可能都會遇到。但願能幫助到那些和我同樣的人!!
0.python-dev安裝(ubuntu)
css

 apt-get install  python-dev 

1.Open(filename,mode)html

報錯實例: f = open('d:\Users\168935495Request.xml','r')python

錯誤信息"SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape"mysql

解決方法: f = open(r'd:\Users\168935495Request.xml','r')web

緣由:文件名中的 \U 開始的字符被編譯器認爲是八進制sql

2.Module Path數據庫

python安裝目錄在C:\Python33,fibo.py文件在E:\Python。django

報錯實例:import fibojson

錯誤信息「ImportError: No module named 'fibo'ubuntu

解決方法:import sys

     sys.path.append('E:\Python')

      import fibo

緣由:須要在sys中配置工做目錄

2.5 不一樣目錄導入模塊

錯誤信息「ImportError: No module named 'fibo'」

解決方法:在目錄下新建空文件__init__.py

3.Python2.7中文不識別

錯誤信息「SyntaxError: Non-ASCII character '\xc9'

解決方法:文件頭#coding=gbk

4.mysqldb 模塊安裝(目前只支持python 2.7)

系統32位的從https://pypi.python.org/pypi/MySQL-python/1.2.4下而後直接安裝

系統64位的從http://arquivos.victorjabur.com/python/modules/MySQL-python-1.2.3.win-amd64-py2.7.exe下而後直接安裝

5.import MySQLdb 

錯誤信息:this is MySQLdb version (1,2,4,'beta',4),but _mysql is version (1,2,3,'final‘,0)

解決方法:刪除\Lib\site-packages下全部的mysqldb,從新安裝

6.格式化

整型數:%d 無符號整型數:%u 八進制:%o 十六進制:%x %X 浮點數:%f科學記數法
字符串: %s 若是沒有什麼特殊需求徹底能夠所有使用’%s‘來標記

7.with用法

with conn:
    conn.execute("insert into sometable values (?,?)",("foo","bar"))
在這個例子中,commit()是在全部with數據塊中的語句執行完畢而且沒有錯誤以後自動執行的,若是出現任何的異常,將執行rollback()操做,再次提示異常

8.文件每次修改後,須要重啓服務

9.python鏈接MySQL鏈接串(注意編碼)

python鏈接MySQL時加上編碼參數 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',                      # 數據庫名,不須要路徑以及後綴的  
        '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模板錯誤

錯誤信息:Requested setting TEMPLATE_DEBUG, but settings are not configured. You must either define

解決方法:from django.conf import settings  
     settings.configure()  

11.設置靜態資源路徑

settings.py

import os.path

TEMPLATE_DIRS = (
#靜態模塊文件存放路徑
os.path.join(os.path.dirname(__file__), 'templates').replace('\\','/'),
)

使用處
from django.template.loader import get_template
 t = get_template('shoplist.html')

12.model設置表名和主鍵自增(django 默認的表是項目名+類名,主鍵是id)

from django.db import models

class Shop(models.Model):
        class Meta:
            db_table='shops'#指定表名,忽略django自動映射的表名(項目_class)
        ShopId  = models.AutoField(primary_key=True,db_column='sid')#指定列名

13.Templates模塊

須要和model對象的屬性一致(大小寫敏感)

 14.Model中的__unicode__(self)

請確保你的每個模型裏都包含 __unicode__() 方法,這不僅是爲了交互時方便,也是由於 Django會在其餘一些地方用 __unicode__() 來顯示對象。

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'商戶名長度不能超過50')
return cleaned_data


form = ShopForm(request.POST,error_class=ErrList)        
  
message= form.errors['__all__'].__unicode__()
              

16.5使用Form驗證表單數據 (表單中的name名稱必須和form類中的名稱一致)

#form.py
class
ShopPicForm(forms.Form): shopname = forms.CharField(label="商戶名",error_messages={"required":u"商戶不可空"}) picname = forms.CharField(label="圖片名",help_text="長度範圍2-20",max_length=20,min_length=2,error_messages={"required":u"圖片名不可空","min_length":u"最小長度2","max_length":u"最大長度20"}) picup = forms.ImageField(label="選擇圖片",error_messages={"required":u"圖片不可空"})
#view.py      
 form = ShopPicForm(request.POST)
 if form.is_valid():      
     #do something
  else:
     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'賬號錯誤'])
#.html
{{form.errors.username.as_text}}

17.Template中使用cleaned_data

  在view.py中使用 form.cleaned_data['鍵名'],template中使用form.cleaned_data.鍵名

 18.加載動態下拉框(數據從數據庫查詢)

#form代碼
 def __init__(self, *args, **kwargs):
        super(ShopForm, self).__init__(*args, **kwargs)  
        self.fields['cid'].choices = [('0','請選擇')]+\
            [(c.cid,c.categoryname) for c in CategoryModel.objects.all()]

#另外一種

CATEGORY_CHOICES = [('0','請選擇')]+[(c.cid,c.categoryname) for c in CategoryModel.objects.all()]
cid = forms.ChoiceField(choices=CATEGORY_CHOICES)

#template代碼
{{form.cid}}
#model代碼
from django.db import models
class CategoryModel(models.Model):
    class Meta:
        db_table="categorys"
    cid  = models.AutoField(primary_key=True)
    categoryname = models.CharField(max_length=20)
    createtime = models.DateTimeField(auto_now_add = True)
    lastmodifytime = models.DateTimeField(auto_now = True)    
    def __unicode__(self):
        return u'%s' % (self.categoryname)

 19.下拉框設置選中

#view.py
form.fields['cid'].choices = [(1,1),(2,2),(3,3)]
form.fields['cid'].initial = [2]#選中第二個

 20.圖片上傳

#model
 url = models.ImageField(upload_to = "%Y/%m/%d",blank=True)#注意此處頭部不要帶/,不然會提示Attempted access to '' denied. #form
 url = forms.ImageField()
#view form = UploadFileForm(request.POST, request.FILES)必需要將request.FILES傳給form的構造函數,才能將文件數據綁定到form.
 if 'picup' in request.FILES:
            image = request.FILES["picup"]
        else:
            image =None
        name = 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.靜態資源(圖片)顯示

#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.生產環境關閉DEBUG,500的錯誤

DEBUG = False,只是這樣會出現500的錯誤,須要在ALLOWED_HOSTS = ['域名'或'ip'或'*']。生產環境推薦使用域名

22.MD5加密

from hashlib import md5

md5('加密字符串').hexdigest()

23.Cookie設置

#設置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>後臺管理</h1>
        <p class="path">
            當前位置:{%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%}
內容
{%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 函數,格式:項目.包.模塊.方法                
)

b)logined方法

def logined(request):
    c = request.COOKIES.get(web.settings.COOKIENAME)
    if c:
        context = {'admin':c}
    else:
        context =  {'admin':"未登陸"}
    return context #返回必須是字典

26.配置多個數據庫

#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')#默認使用的是default

Shop.objects.all().using('backup').order_by('-ShopId')#使用其餘數據庫

 27.Cookie設置後跳轉Url(這個問題糾結了好久)

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纔會生效

 29.提交表單報錯:RuntimeError: You called this URL via POST,
      but the URL doesn’t end in a slash and you have APPEND_SLASH set.

將from的action地址改成/結尾的就能夠了
或者
修改settings:APPEND_SLASH=False

30.Url配置name參數,

#urls.py
url(r'^$', 'wetrip.views.home.index', name='home'),
#template
<a href="{%url 'home'%}">首頁</a>
之後url地址發生變化,只須要修改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.目錄建立

#多層建立目錄函數os.makedirs(path)。當父目錄不存在的時候os.mkdir(path)不會建立,os.makedirs(path)則會建立父目錄。
def mkdir(path):
    # 引入模塊
    import os
    # 去除首位空格
    path=path.strip()
    # 去除尾部 \ 符號
    path=path.rstrip("\\")
 
    # 判斷路徑是否存在
    # 存在     True
    # 不存在   False
    isExists=os.path.exists(path)
 
    # 判斷結果
    if not isExists:
        # 若是不存在則建立目錄
        print path+' 建立成功'
        # 建立目錄操做函數
        os.makedirs(path)
        return True
    else:
        # 若是目錄存在則不建立,並提示目錄已存在
        print path+' 目錄已存在'
        return False
 

 33.返回403

1. 在settings.py裏面的MIDDLEWARE_CLASSES中加入django.middleware.csrf.CsrfResponseMiddleware

2. 在settings.py裏面的MIDDLEWARE_CLASSES中去掉django.middleware.csrf.CsrfViewMiddleware

 34.返回Josn格式數據

#view.py
from django.utils import simplejson

json={'ret':ret,'save_name':new_name}
#支持中文
return HttpResponse(simplejson.dumps(json,ensure_ascii = False))

 35.html轉義

#template
{% autoescape off %}
coding...
{% endautoescape %}
這裏的off 參數代表被autoescape包含的信息都不須要執行HTML轉義。on 參數表示須要執行HTML轉義

 36.訪問遠程圖片

import cStringIO, urllib2, Image

url = 'remote picture'
file = urllib2.urlopen(url)
tmpIm = cStringIO.StringIO(file.read())
im = Image.open(tmpIm)

 37.‘gbk' codec can't encode character 錯誤

#忽略特殊字符
str.encode('gbk','ignore')

 38.獲取Post name相同的值(如多個checkbox)

#view.py
request.POST.getlist('name')

 39.建立Django(path到django目錄下)

django-admin.py startproject mysite

40.中文輸出

  u'中文'

41.模板註釋

{# 文字#}註釋的內容不會在模板渲染時輸出。註釋不能跨多行

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

 

未完待續...

相關文章
相關標籤/搜索