我正在尝试为django中的帖子创建评论模型。我想打印用户名和评论。
这是我的评论模型
class Comment(models.Model):
item = models.ForeignKey('app.Item', related_name='comments')
user = models.ForeignKey('auth.User', blank=True, null=True)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
approved_comment = models.BooleanField(default=False)
def approve(self):
self.approved_comment = True
self.save()
def __str__(self):
return self.text
这是我的观点
def add_comment_to_post(request, pk):
item = get_object_or_404(Item, pk=pk)
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.user = user.username
comment.item = item
comment.save()
return redirect('item_detail', pk=item.pk)
else:
form = CommentForm()
return render(request, 'app/add_comment_to_post.html', {'form': form}
)
这是我的HTML代码
{% for comment in item.comments.all %}
{% if user.is_authenticated or comment.approved_comment %}
<div class="comment">
<div class="date">
{{ comment.created_date }}
{% if not comment.approved_comment %}
<a class="btn btn-default" href="{% url 'comment_remove' pk=comment.pk %}"><span class="glyphicon glyphicon-remove"></span></a>
<a class="btn btn-default" href="{% url 'comment_approve' pk=comment.pk %}"><span class="glyphicon glyphicon-ok"></span></a>
{% endif %}
</div>
<p> {{comment.user}} <p>
<p>{{ comment.text|linebreaks }}</p>
</div>
{% endif %}
{% empty %}
<p>No comments here yet :(</p>
{% endfor %}