django视图没有返回一个HttpResponse对象。它返回了None

时间:2014-11-14 09:28:58

标签: python django view

以下是我的观点:

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:继续正确的缩进,它不会给出错误..

需要帮助......

1 个答案:

答案 0 :(得分:4)

您在这里比较username 字段user 对象

if thumb.username == request.user:
  • thumb.username可能会返回字符串,例如'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))