我正在开发 Django 应用程序。我已经花了大约 40-50 个小时研究 Django,现在我正在准备一个应用程序!
但是,我开始遇到“更严重”的错误,有些人可能会这样调用它们,因为我无法从我的堆栈跟踪中找出真正的问题所在。
基本上,我点击我页面上的一个链接,弹出这个错误:
请求方式:GET
请求网址:/accounts/profile/
Django 版本:1.5.1
异常类型:ValueError
异常值:
* View userprofile.views.user_profile 没有返回 HttpResponse 对象。*
这让我相信错误出在我的 View 文件中,除了我正在逐行遵循教程,而且我相信错误可能出在如何使用 forms.py 来创建 HttpResponse 对象.
简而言之,代码是,
form = UserProfileForm(request.POST, instance=request.user.profile)
...
args = {}
args.update(csrf(request)) // security token
args['form'] = form
return render_to_response('profile.html', args)
profile.html 也绝对没问题,我测试过,我基本上是从显示有效用户登录的 loggedin.html 页面调用它。
非常感谢您的帮助 所以,我通常不问问题,但我已经在这个问题上停留了 5-6 个开发小时。尽量不要 mock 我不理解这个可能很简单但对初学者来说是隐藏的错误:)
此外,如果您能说明您是如何解决这个错误的,我更希望在回复中说明您是如何解决这个错误的,尤其是说明我的想法是如何以及根本误解在哪里。
在你的回答中,只引用文档的特定实例,因为我已经做了很多搜索,但也许它并没有缩小到我的问题所在 :D
再次感谢,
詹姆斯
评论一:教程
Here is the tutorial我指的是。我陷入了识别错误的困境,因为在我尝试单击超链接之前,我拥有所有代码并且一切正常。我没有经验错误是从哪里来的。
二评:相关代码
userprofile/views.py
def user_profile(request):
if request.method=='POST':
form = UserProfileForm(request.POST, instance=request.user.profile)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/loggedin')
else:
user = request.user
profile = user.profile
form = UserProfileForm(instance=profile)
args = {}
args.update(csrf(request)) // security token
args['form'] = form
return render_to_response('profile.html', args)
myapp urls.py , userprofile urls.py
(r'^accounts/', include ('userprofile.urls')),
...
url(r'^profile/$', 'userprofile.views.user_profile'),
最佳答案
如果那确实是您的 View 代码,那是一个简单的缩进错误。应该是:
def user_profile(request):
if request.method=='POST':
form = UserProfileForm(request.POST, instance=request.user.profile)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/loggedin')
else:
user = request.user
profile = user.profile
form = UserProfileForm(instance=profile)
args = {}
args.update(csrf(request)) // security token
args['form'] = form
return render_to_response('profile.html', args)
发生的事情是,当 request.METHOD 为 GET
时,初始 if 上没有 else
子句,因此 View 函数结束时不返回任何内容。相反,您想创建表单,将其添加到上下文中并呈现它 - 因为它是一个 GET
请求或因为表单中存在错误,并且您想重新呈现上下文以显示这些错误并允许用户更正它们。
关于python - Django 手动调试流程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17688928/