2014-11-14 85 views
2

這是我的觀點:django視圖沒有返回HttpResponse對象。它返回無不是

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)) 

當我做到這一點給出了錯誤didnt返回HttpResponse對象。但是,當我刪除行 if thumb.username == request.user:並繼續正確的縮進它不提供錯誤..

需要幫助...

+1

當'如果thumb.username == request.user:'爲true並且代碼朝那個方向運行,會發生什麼? –

+0

問題是如果if爲false時發生了什麼,沒有返回 – AlvaroAV

回答

4

你比較的usernameuser對象在這裏:

if thumb.username == request.user: 
  • thumb.username可能返回一個字符串'JohnDoe'
  • request.user返回一個對象,如:<User: johndoe>

所以if似乎是假ALLWAYS

爲了解決這個問題,你應該做的:

if thumb.username == request.user.username: 
  • 如果第一個條件爲假,會發生什麼?你需要一個替代的回報,相同的縮進if thumb.username...

你得到的無而不是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)) 
+0

當我做最後一次返回時它說上下文表單在賦值之前被使用...... – gamer

+0

在最後一次返回中,您應該只返回一個錯誤變量或初始化一個空表格 – AlvaroAV

+0

ohk明白了......幫我..很多.. – gamer

相關問題