Django开发中常见的几种报错和解决方式

本文详细介绍了在Django开发过程中遇到的五种常见错误,包括RuntimeError关于URL末尾斜杠的问题、POST请求中nid丢失问题、UnicodeDecodeError编码错误、MySQL连接错误以及QuerySet对象无status_code属性的问题,并提供了相应的解决方法。

Django报错一:

RuntimeError: 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:8090/add_user/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings.

解决办法:

1.确保你的add_user.html中form表单的action是否以/结尾

<form action="/add_user/" method="post" novalidate>

2.修改settings.py,添加以下内容

APPEND_SLASH=False

Django报错二:

编辑好数据提交时,POST请求后,表单里action="/edit_user-{{ nid }}/"中的nid没拿到

后端报错:Not Found: /edit_user-/

原因:先前GET请求edit_user.html页面时,函数没有返回nid,所以post的时候nid拿不到

def edit_user(request,nid):

    if request.method == "GET":

        data = models.UserInfo.objects.filter(id=nid).first()

        obj = UserForm({'username':data.username,'email':data.email})

        return render(request,'edit_user.html',{'obj':obj,'nid':nid})

Django报错三:

针对django2.2报错:UnicodeDecodeError: 'gbk' codec can't decode byte 0xa6 in position 9737: ill....

正式解决方式:

卸载django后重新安装新的版本

临时着急解决方式:

打开django/views下的debug.py文件,转到line331行:

   with Path(CURRENT_DIR, 'templates', 'technical_500.html').open() as fh

  将其改成:

    with Path(CURRENT_DIR, 'templates', 'technical_500.html').open(encoding="utf-8") as fh

就成功了。

Django报错四:

django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)"

解决方式:

把settings里连接mysql的host由localhost改为127.0.0.1

Django报错五:

'QuerySet' object has no attribute 'status_code'

解决方式:

需要把得到的列表数据遍历,model_to_dict(data)转换成dict类型再return

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值