Django开发过程中的一些bug及解决方法

在使用django开发一个交易平台的过程中,遇到各种各样的问题,其中有比较复杂的问题也有疏忽导致的比较简单的bug,记录下来,希望有所帮助。

错误:

   "A model can't have more than one AutoField."
AssertionError: A model can't have more than one AutoField.

删除重复AUTO_ID后解决。

manage.py makemigrations BookTrade
Migrations for ‘BookTrade’:
BookTrade\migrations\0001_initial.py:
- Create model BOOK
- Create model TRADE
- Create model USR
- Add field BuyerId to trade
- Add field Owner to book

manage.py migrate BookTrade
Operations to perform:
Apply all migrations: BookTrade
Running migrations:
Applying BookTrade.0001_initial… OK

错误:

TypeError at /regist/
render() takes at least 2 arguments (1 given)

解决方法:传一个空字典,或选择HttpResponse:

错误:

TemplateDoesNotExist at /regist/
{'key': 15340}

解决:

return render(request,'Regist.html',stk)

原因参数错误。

错误

RuntimeError at /regist
You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to 127.0.0.1:3000/regist/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings.

原因:url结尾未加/

错误:

Forbidden (403)
CSRF verification failed. Request aborted.

解决:
Form中添加 {% csrf_token %}

错误:

TypeError at /regist/
'Telphone' is an invalid keyword argument for this function

解决:拼写问题,应为TelPhone

错误:

Variable    Value
args    ("'fdsf'", '416816', "'dfs'", "'[email protected]'", "'146161'")
db  <_mysql.connection open to 'localhost' at 4228fc0>
exc <class '_mysql_exceptions.OperationalError'>
query   "INSERT INTO `BookTrade_usr` (`Name`, `StuId`, `PassWord`, `Email`, `TelPhone`) 
VALUES ('fdsf', 416816, 'dfs', '[email protected]', '146161')"
res None
self    <MySQLdb.cursors.Cursor object at 0x04333470>
value   OperationalError(1054, "Unknown column 'TelPhone' in 'field list'")

原因:models有改动,未同步数据库
解决:

manage.py makemigrations BookTrade
Did you rename usr.TlePhone to usr.TelPhone (a CharField)? [y/N] y
Migrations for 'BookTrade':
  BookTrade\migrations\0002_auto_20170404_1742.py:
- Rename field TlePhone on usr to TelPhone
manage.py migrate BookTrade
Operations to perform:
  Apply all migrations: BookTrade
Running migrations:
  Applying BookTrade.0002_auto_20170404_1742... OK

错误:

UnicodeDecodeError at /login/
'utf8' codec can't decode byte 0xbb in position 74: invalid start byte

原因:
views文件的默认编码为gb2312,导致错误。
解决方法: rsp[‘error’] = ‘账号或密码错误’.decode(‘gb2312’).encode(‘utf-8’) 或者改变views.py文件编码,这里选择第二种。

错误:

AttributeError at /login/
'QuerySet' object has no attribute 'Name'

原因:
QuerySet 是一個 Set。
改为: rsp[‘usrname’] = test.all()[0].Name
get方法是只返回一个,filter是返回一个或多个,两个都是在没有的情况下返回错误DoesNotExists。但是get由于只返回一个,如果有多个匹配的则返回MultipleObjectsReturned。并且在对于get方法,有一个快捷方法就是get_object_or_404,如果object不存在就会自动返回404;同样对于filter有对应的是get_list_or_404。

错误:

TypeError at /sale/
add() takes exactly 1 argument (2 given)

错误代码:

url(r'^(add|sale)/$',views.add),

错误原因:
不支持多个URL映射?

错误:

MultiValueDictKeyError at /sale/
"'bookpublish'"

原因:不存在的post_keyname

错误:

TypeError at /sale/
create() takes exactly 1 argument (2 given)

原因:参数错误

错误:

AttributeError at /sale/
'dict' object has no attribute 'Owner'

原因:Owner为USR的外键,应传入usrid

错误:

ValueError at /sale/
Cannot assign "5": "BOOK.Owner" must be a "USR" instance.

解决方法:
• 普通数据项:直接插入
• 外键数据项:先获取要插入的外键(对象),然后和普通键一起插入
• 多对多数据项:获取要插入的多对多数据项,待表中普通数据项和外键数据项save后,使用.add方法加入

BOOK.objects.create(Owner = test.all()[0], BookName = data['BookName'], BookAuthor = data['BookAuthor'], BookPublish = data['BookPublish'], BookBrief = data['BookBrief'],)

错误:

TypeError at /regist/
'UsrId' is an invalid keyword argument for this function

原因:拼写错误,应为UsrID

错误:

AttributeError at /regist/
'MultiValueDict' object has no attribute '_committed'

错误代码:usrimg = request.FILES
解决:usrimg = request.FILES.get('img')

错误:

<img src="{{ usrimg }}" style="height:50px; width:50px;"/>

图片不显示
解决:

<img src="/media/{{ usrimg }}" style="height:50px; width:50px;"/>

注意:

from django.conf.urls.static import static

urlpatterns = [
    url(r'^admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

错误:

TYPEERROR: In order to allow non-dict objects to be serialized set the safe parmeter to False 

错误代码:

return JsonResponse(rsp)

更正:

return JsonResponse(rsp, safe=False)

增加safe=false,使其接受列表。

错误:

TypeError: <ImageFieldFile: None> is not JSON serializable

错误原因:responseJSON不接受对象,而查询到的ImgField是一个Field对象
解决:使用str()将Field转成字符型。

错误:

DisallowedHost at /main
Invalid HTTP_HOST header: '121.49.127.140:3000'. You may need to add u'121.49.127.140' to ALLOWED_HOSTS

解决:在settings.py中添加:

ALLOWED_HOSTS = ['121.49.127.140',
]

异常:

manage.py makemigrations BookTrade
You are trying to add a non-nullable field ‘BookPrice’ to book without a default; we can’t do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
2) Quit, and let me add a default in models.py
Select an option:
原因:这是因为修改模型后没有添加default值。

TypeError at /book/sale/
‘WeChat’ is an invalid keyword argument for this function
原因:数据模型中不存在的键,一般是因为拼写错误。

IndexError at /book/details/
list index out of range
第1种可能情况
list[index]index超出范围
第2种可能情况
list是一个空的 没有一个元素
进行list[0]就会出现该错误

错误:

AttributeError: ‘BOOK’ object has no attribute ‘update’

原因:
在调用models的方法时未加objects

错误:
Manager isn’t accessible via BOOK instances
原因:
Managers只能通过model class来访问,而不能通过model的实例化对象来访问,这主要是为了区分表级与记录级的操作。
对model来说,Manager管理器是产生QuerSet的主要方式,如Blog.objects.all()返回数据库中包含所有Blog对象的一组QuerySet。

更改:

      #  book.objects.update(Lock = False)
         BOOK.objects.filter(BookId = book.BookId).update(Lock = False)

猜你喜欢

转载自blog.csdn.net/vic_torsun/article/details/70555387