Reputation:
I was trying to make deleting comments function, when user clicks button then it deletes relevant item and redirects to main page. However I got this error message and I'm spending time to fix this. Please review my code and if there is something wrong.
error message
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'),
templates
<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
I added def detail in 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)
Upvotes: 1
Views: 187
Reputation: 374
if 'username' in request.session:
...
context = {
'item': item,
'comments': comments,
}
Here, the context
is only created if 'username' in request.session
is True
.
Since you're returning a context
variable, you'll need to create it for the case when username
is not in request.session
too. Otherwise context
will be missing if the above codeblock returns False
, and subsequently cause that UnboundLocalError
.
Upvotes: 1