Django的字符转换抛出异常问题
在对某变量赋予初值时,常会设置默认初值为''(即空字符串),
当该变量在被获取后需要与数字类型做判断时,需要将该变量转换为int类型,
但空串转int会抛出异常,此时可将该变量初值设为0.
例如:
class AddFavView(View): """ 用户收藏,取消收藏 """ def post(self, request): fav_id = request.POST.get('fav_id', 0) fav_type = request.POST.get('fav_type', 0) if not request.user.is_authenticated(): #判断用户登录状态 return HttpResponse('{"status":"fail", "msg":"用户未登录"}', content_type='application/json') exist_records = UserFavorite.objects.filter(user=request.user, fav_id=int(fav_id), fav_type=int(fav_type)) if exist_records: #如果记录已经存在,则表示用户取消收藏 exist_records.delete() return HttpResponse('{"status":"success", "msg":"收藏"}', content_type='application/json') else: user_fav = UserFavorite() if int(fav_id) > 0 and int(fav_type) > 0: user_fav.user = request.user user_fav.fav_id = int(fav_id) user_fav.fav_type = int(fav_type) user_fav.save() return HttpResponse('{"status":"success", "msg":"已收藏"}', content_type='application/json') else: return HttpResponse('{"status":"fail", "msg":"收藏出错"}', content_type='application/json')
报错截图: