gpt4 book ai didi

python - View 未返回 HttpResponse 对象错误

转载 作者:太空宇宙 更新时间:2023-11-03 10:51:57 30 4
gpt4 key购买 nike

我正在将 excel 数据导入 MySQL 数据库。这样做时,我看到一个错误。

我的 views.py 文件:

db = MySQLdb.connect(host="localhost", 
user="root",
passwd="",
db="upload")
test = 'c'

def list(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile = request.FILES['docfile'])
newdoc.save()
newdoc = newdoc.docfile.name
newdoc = str(newdoc)
wb = xlrd.open_workbook(newdoc)
sh = wb.sheet_by_index(0)
c = 1
while c < len(sh.col(0)):
first = sh.col_values(0)[c]
second = sh.col_values(1)[c]
x = db.cursor()
db.set_character_set('utf8')
x.execute('SET NAMES utf8;')
x.execute('SET CHARACTER SET utf8;')
x.execute('SET character_set_connection=utf8;')
x.execute("INSERT INTO testcont_content(title, description) VALUES('%s','%s');"%(first,second))
db.commit()
c=c+1
return HttpResponseRedirect(reverse('upload.views.list'))
else:
form = DocumentForm() # A empty, unbound form
documents = Document.objects.all()
return render_to_response('upload/list.html',{'documents': documents, 'form': form, 'test': test,},context_instance=RequestContext(request))

我在“return HttpResponseRedirect(reverse('upload.views.list'))”行收到错误:

Internal Server Error: /upload/list/
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 133, in get_response
raise ValueError("The view %s.%s didn't return an HttpResponse object." % (callback.__module__, view_name))
ValueError: The view upload.views.list didn't return an HttpResponse object.
[06/Jun/2014 10:39:20] "GET /upload/list/ HTTP/1.1" 500 60044

我的 forms.py 文件是:

class DocumentForm(forms.Form):
docfile = forms.FileField(
label='Select a file',
help_text='max. 42 megabytes'
)

urls.py 文件:

urlpatterns = patterns('',
url(r'^list/$', views.list, name='list'),
)

我不知道我在这里做错了什么。

最佳答案

您需要在每次请求时返回一个HttpResponse 对象(或一个子类,如HttpResponseRedirect)。在您的代码中,您正在检查请求是否通过 POST 发送,但您忘记返回响应。你的观点应该是这样的:

def list(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile = request.FILES['docfile'])
# ... Your process
return HttpResponseRedirect(reverse('upload.views.list'))
else:
form = DocumentForm() # A empty, unbound form

# We reach there when the HttpResponseRedirect has not been called
documents = Document.objects.all()
return render_to_response('upload/list.html',
{'documents': documents, 'form': form, 'test': test,},
context_instance=RequestContext(request))

关于python - View 未返回 HttpResponse 对象错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24074631/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com