【发布时间】:2021-02-02 20:19:53
【问题描述】:
如何在不刷新页面的情况下在我的 Django 网站中添加 cmets?
这是我的代码:
VIEW.PY
@login_required
def comments(request, post_id):
"""Comment on post."""
post = get_object_or_404(Post, id=post_id)
user = request.user
comments = Comment.objects.filter(post=post).order_by('-date')#comment
if request.method == 'POST':#Comments Form
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.user = user
comment.save()
messages.success(request, 'Comment has been added successfully.')
return HttpResponseRedirect(reverse('core:comments',args=[post_id]))
else:
form = CommentForm()
template = loader.get_template('post/comments.html')
context = {'post':post,'form':form,'comments':comments,}
return HttpResponse(template.render(context, request))
COMMENTS.HTMl
表单部分:
<div class='commentsection' >
<strong>
<form action="{% url 'core:comments' post.id %}" method='post' id=comment-form >
{% csrf_token %}
{% bootstrap_form form %}
</form>
<br/>
<br/>
</strong>
</div>
评论部分:
{% for comment in comments %}
<div class="card mb-3" style="width: 30rem;">
<div class="row no-gutters">
<small> <a style="color: black;" href="{% url 'core:user_profile' comment.user %}"><img src="{{comment.user.profile.profile_pic.url}}" width=50 height=50 class="profile-image img-circle " style="object-fit: cover; float: auto; "><strong style="font-size: 18px;" > @{{comment.user}} </strong></a> </small> <small><span class="glyphicon glyphicon-time"></span> {{ comment.get_date }}</small>
</div>
<div class="card-body" style="width:100%; padding-left:20%; margin-top:-8%; word-break: break-all; color:black; " >
<h5 class="card-text">
{{ comment.comment }}</h5>
<small ><a href="{% url 'core:replies' comment.id %}"> Replies </a> [{{comment.total_replies}}] </small
</div>
</div>
</div>
<br/><br/>
{% empty %}
<center>
No commnets
</center>
{% endfor %}
我的问题:
- 在不刷新页面的情况下添加 cmets。
- 在评论部分自动添加新添加的 cmets,无需刷新页面。
提前致谢!
【问题讨论】: