Это конечный результат моего текущего приложения для комментариев в Django:
Как сделать так, чтобы дочерние элементы родительских комментариевбыть вложенными друг в друга.
Это связанные коды, если вы хотите немного их изменить:
models.py
class Comment(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
timestamp = models.DateTimeField(auto_now_add=True)
content = models.TextField()
parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE)
# content types framework
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
def children(self):
return Comment.objects.filter(parent=self)
views.py
def blog_detail(request, blog_slug):
blog = get_object_or_404(Blog, slug=blog_slug)
session_key = 'blog_views_{}'.format(blog.slug)
if not request.session.get(session_key):
blog.blog_views += 1
blog.save()
request.session[session_key] = True
content_type = ContentType.objects.get_for_model(Blog)
object_id = blog.id
# look at CommentManager as well
comments = Comment.objects.filter(content_type=content_type, object_id=object_id).filter(parent=None)
initial_data = {
'content_type':blog.get_content_type,
'object_id': blog.id
}
form = CommentForm(request.POST or None, initial=initial_data)
if form.is_valid():
c_t = form.cleaned_data.get('content_type')
content_type = ContentType.objects.get(model = c_t)
obj_id = form.cleaned_data.get('object_id')
content = form.cleaned_data.get('content')
parent_obj = None
try:
parent_id = int(request.POST.get('parent_id'))
except:
parent_id = None
if parent_id:
parent_qs = Comment.objects.filter(id=parent_id)
if parent_qs.exists() and parent_qs.count() == 1:
parent_obj = parent_qs.first()
new_comment = Comment.objects.create(
user = request.user,
content_type = content_type,
object_id = obj_id,
content = content,
parent=parent_obj,
)
return HttpResponseRedirect(new_comment.content_object.get_absolute_url())
context = {
'blog': blog,
'categories': get_category_count(),
'comments':comments,
'form':form,
}
return render(request, 'blogs/blog-detail.html', context)
и html page
{% for i in comments %}
<div style="border-left: 4px solid #ccc;background-color: #f3f3f3; padding: 7px;">
{{ i.content }} <br>
<small class="text-secondary">
<i class="fa fa-user"></i> {{ i.user|title }} | <i class="fa fa-clock"></i> {{ i.timestamp|timesince }} ago |
{% if i.children.count >= 0 %} {{ i.children.count }} comment(s) {% endif %} |<a href="#" class="reply-btn">reply</a>
</small>
<div class="replies" style="display:none !important;">
{% for child in i.children %}
<div style="border-left: 4px solid #ccc;background-color: #f3f3f3; padding: 7px;">
{{ child.content }} <br>
<small class="text-secondary">
<i class="fa fa-user"></i> {{ child.user|title }} | <i class="fa fa-clock"></i> {{ child.timestamp|timesince }} ago
</small>
</div>
{% endfor %}
<form method="POST">
{% csrf_token %}
{{ form|crispy }}
<input type="hidden" value="{{ i.id }}" name="parent_id">
<input type="submit" value="Submit" class="btn btn-success">
</form>
</div>
</div>
<hr>
{% endfor %}
Было бы здорово помочь мне, как добавить вложенные ответы для родительских комментариев, спасибо.
edit: Вы рекомендуете другие решения?какая-нибудь сторонняя библиотека, которая может мне помочь с этим?