django報錯解決辦法集錦


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

 apt-get install  python-dev 

1.Open(filename,mode)

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

錯誤信息"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 開始的字符被編譯器認為是八進制

2.Module Path

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

報錯實例:import fibo

錯誤信息“ImportError: No module named 'fibo'”

解決方法: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參數,

1
2
3
4
5
#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.目錄創建

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#多層創建目錄函數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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM