我有一个Django views.py文件,在其中我渲染页面并基于模型创建对象。用于创建这些对象的数据来自我导入的python文件(price.py)中的函数。
由于某种原因,当我自己运行脚本时,我能够将字符串转换为浮点数(该值将类似于“ 4124.3123”)。但是,将这个确切的代码作为导入运行会导致值错误。
所以我的文件结构看起来像这样:
app
views.py
price.py
models.py
urls.py
错误:
File "/home/joe/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/joe/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/joe/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/joe/Documents/pcbuilder/cpu/views.py", line 40, in homepage
itemlist = canada('https://www.canadacomputers.com/index.php?cPath=4_64')
File "/home/joe/Documents/pcbuilder/cpu/price.py", line 57, in canada
PRICES = [float(str(i).split('>')[-3].strip('<strong/>').replace('*','').replace(',','.')[1:]) for i in PRICE]
File "/home/joe/Documents/pcbuilder/cpu/price.py", line 57, in <listcomp>
PRICES = [float(str(i).split('>')[-3].strip('<strong/>').replace('*','').replace(',','.')[1:]) for i in PRICE]
ValueError: could not convert string to float: '1.299.00'
以下是我的价格表中令人烦恼的清单信息:
def canada():
# some code
PRICES = [float(str(i).split('>')[-3].strip('<strong/>').replace('*','').replace(',','.')[1:]) for i in PRICE]
#some code
#return type: dictionary
这是我的views.py:
from django.shortcuts import render
from django.http import HttpResponse
from .models import cpu
from django.template import loader
import os
import django
from .price import canada
def createobject(graph):
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE','pcbuilder.settings')
import django
django.setup()
def add_data(data1, data2, data3):
d, created = cpu.objects.get_or_create(item=data1, price=data2,website=data3)
print("- Data: {0}, Created: {1}".format(str(d), str(created)))
return d
add_data('h','h','h')
for i in graph:
add_data(str(i), str(graph[i]), 'canada computers')
def homepage(request):
print('Receiving CPUs')
itemlist = canada('https://www.canadacomputers.com/index.php?cPath=4_64')
print('Received CPUs')
createobject(itemlist)
items = cpu.objects.all
template = loader.get_template('cpu.html')
context = {
'items': items,
}
return HttpResponse(template.render(context, request))
注意:canada()是price.py中的函数