2017-02-16 69 views
1

我試圖刪除註釋功能,當用戶點擊按鈕,然後刪除相關項目並重定向到主頁面。但是,我收到了這個錯誤消息,我正在花時間解決這個問題。請檢查我的代碼,如果有什麼問題。Django:刪除對象後無法重定向主頁

錯誤消息

UnboundLocalError at /blog/detail/18/ 
local variable 'context' referenced before assignment 

views.py

@login_required 
def delete_comment(request, comment_no): 
    comment = Comment.objects.get(pk=comment_no).delete() 
    return redirect('blog/home.html') 

urls.py

url(r'^delete_comment/(?P<comment_no>[0-9]+)/$', views.delete_comment, name='delete_comment'), 

模板

<form action="{% url 'blog:delete_comment' %}" method="post"> 
     {% csrf_token %} 
     <input type="hidden" name="comment_no" value="{{ comments.comment_no }}" /> 
     <button type="submit">delete</button> 
</form> 

EDIT 01

我在views.py

@login_required 
def detail(request, article_no): 
    if not request.user.is_authenticated(): 
     return redirect_to_login(next, 'blog/login.html') 
    else: 
     user = request.user 

    if 'username' in request.session: 
     username = request.session['username'] 
     item = get_object_or_404(Article, pk=article_no) 
     item.hit = Article.objects.filter(pk=article_no).update(hit = item.hit+1) 
     no = article_no 
     comments = Comment.objects.filter(article_no=article_no) 
     context = { 
      'item': item, 
      'comments': comments, 
      } 
    return render(request, 'blog/detail.html', context) 
+1

你可以分享查看方法的細節?錯誤指定那裏有什麼問題 – Fallen

+0

@Fallen我在views.py中添加了detail方法。 – camila

+0

這是您在'def detail'中使用的確切縮進嗎?你的第二個「if」塊略有偏差。 – ooknosi

回答

1
if 'username' in request.session: 
    ... 
    context = { 
     'item': item, 
     'comments': comments, 
     } 

在這裏加入DEF詳細地,context僅創建if 'username' in request.sessionTrue

由於您要返回context變量,因此您需要爲username也不在request.session中的情況創建它。否則context將丟失,如果上述代碼塊返回False,並隨後導致該UnboundLocalError