django 视图没有返回 HttpResponse 对象。它返回 None 而不是
Posted
技术标签:
【中文标题】django 视图没有返回 HttpResponse 对象。它返回 None 而不是【英文标题】:django view didn't return an HttpResponse object. It returned None instead 【发布时间】:2014-11-14 09:28:58 【问题描述】:这是我的看法:
def GeneralUserPictureChange(request, pk, username):
thumb = GeneralUser.objects.get(pk=pk)
if thumb.username == request.user:
if request.method == 'POST':
form = GeneralUserPictureChangeForm(request.POST, request.FILES)
if form.is_valid():
thumb.thumbnail = form.cleaned_data['thumbnail']
thumb.save()
return redirect("user_profile", pk, username)
else:
return render_to_response("gnu_picture_change.html", "form":form, "basic_info":thumb, context_instance=RequestContext(request))
else:
form = GeneralUserPictureChangeForm()
return render_to_response("gnu_picture_change.html", "form":form, "basic_info":thumb, context_instance=RequestContext(request))
当我这样做时,错误没有返回 HttpResponse 对象。但是当我删除线
if thumb.username == request.user:
并继续进行适当的缩进它不会给出错误..
需要帮助...
【问题讨论】:
当if thumb.username == request.user:
为真并且代码朝那个方向发展时会发生什么?
问题是当if为假时会发生什么,没有返回
【参考方案1】:
您在此处比较 username
field 和 user
object:
if thumb.username == request.user:
thumb.username
可能会返回一个 string 像 'JohnDoe'
request.user
返回一个对象,如:<User: johndoe>
所以if
似乎是假的ALLWAYS
要解决此问题,您应该这样做:
if thumb.username == request.user.username:
如果第一个条件为假会发生什么?您需要一个替代返回,与if thumb.username...
相同的缩进
你得到的是 None 而不是 HttpResponse,因为如果第一个 if
为假,你没有返回值
def GeneralUserPictureChange(request, pk, username):
thumb = GeneralUser.objects.get(pk=pk)
if thumb.username == request.user:
if request.method == 'POST':
form = GeneralUserPictureChangeForm(request.POST, request.FILES)
if form.is_valid():
thumb.thumbnail = form.cleaned_data['thumbnail']
thumb.save()
return redirect("user_profile", pk, username)
else:
return render_to_response("gnu_picture_change.html", "form":form, "basic_info":thumb, context_instance=RequestContext(request))
else:
form = GeneralUserPictureChangeForm()
return render_to_response("gnu_picture_change.html", "form":form, "basic_info":thumb, context_instance=RequestContext(request))
# You need a return like this one, in case the first if is false
return render_to_response("gnu_picture_change.html", "Error":'Not valid username', context_instance=RequestContext(request))
【讨论】:
在最后的返回中你应该只返回一个错误变量或者初始化一个空表单以上是关于django 视图没有返回 HttpResponse 对象。它返回 None 而不是的主要内容,如果未能解决你的问题,请参考以下文章
python django ajax:ValueError:视图没有返回 HttpResponse 对象。它返回 None 而不是
Django ValueError 视图 todo_lists.views.visualisation 没有返回 HttpResponse 对象。它返回 None 而不是