I wanted to pass two objects to templates, so I put theme in the context and try to send them but failed. I tried few times but it seems like user get objects but comment is always empty even though there are some data in db.
This is 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)
#comment = Comment.objects.filter(pk=article_no).order_by('comment_no')
comment = Comment.objects.all()
context = {
'item': item,
'comment': comment,
}
return render(request, 'blog/detail.html', context)
this is models.py
from datetime import datetime
from django.db import models
from django.template.defaultfilters import default
class Article(models.Model):
no = models.AutoField(primary_key=True)
title = models.CharField(max_length=50)
content = models.CharField(max_length=300)
writer = models.CharField(max_length=50)
is_visible = models.BooleanField(default=True)
created_date = models.DateTimeField(editable=False, default=datetime.now())
hit = models.IntegerField(default=1)
class Comment(models.Model):
article_no = models.IntegerField(default=1)
comment_no = models.AutoField(primary_key=True)
comment_writer = models.CharField(max_length=50)
comment_body = models.CharField(max_length=300)
comment_date = models.DateTimeField(editable=False, default=datetime.now())
template
{{ item.title }}
{{ item.no }}
{{ item.writer }}
{{ item.hit }}
{{ item.created_date }}
{{ item.content }}
{% if comments %}
{% for comment in comments %}
{{ comment.comment_no }}
{{ comment.comment_writer }}
{{ comment.comment_body }}
{{ comment.comment_date }}
{% endfor %}
{% else %}
<div class="row">no comment.</div>
{% endif %}