Не уверен, что я сделал не так. Я создаю систему комментариев, чтобы пользователи могли оставлять комментарии к сообщению и отвечать на этот комментарий. Все прекрасно работает, за исключением случаев, когда пользователь отвечает на какой-то комментарий, что ответ отображается как один комментарий. (И он также отображается как ответ), поэтому, если я отвечу на комментарий «как вы» с сообщением «хорошо», то я создал два «хороших». один как ответ. один как единственный комментарий. Я просмотрел свой код, но я понятия не имею, почему это происходит. Любая помощь будет высоко оценен. Спасибо /. Вот мой код.форма отправлена и она была сделана дважды. Почему это происходит
views.py
def post(request, slug):
user = get_object_or_404(User,username__iexact=request.user)
try:
profile = MyProfile.objects.get(user_id=request.user.id)
# if it's a OneToOne field, you can do:
# profile = request.user.myprofile
except MyProfile.DoesNotExist:
profile = None
post = get_object_or_404(Post, slug=slug)
post.views += 1 # increment the number of views
post.save() # and save it
path = request.get_full_path()
comments = Comment.objects.filter(path=path)
#comments = post.comment_set.all()
comment_form = CommentForm(request.POST or None)
if comment_form.is_valid():
parent_id = request.POST.get('parent_id')
parent_comment = None
if parent_id is not None:
try:
parent_comment = Comment.objects.get(id=parent_id)
except:
parent_comment = None
comment_text = comment_form.cleaned_data['comment']
new_comment = Comment.objects.create_comment(
user=MyProfile.objects.get(user=request.user),
path=request.get_full_path(),
text=comment_text,
post = post,
parent = parent_comment
)
comment_form = CommentForm()
return HttpResponseRedirect(post.get_absolute_url())
for c in comments:
c.get_children()
context_dict = {
'post' :post,
'profile' :profile,
'comments' : comments,
'comment_form':comment_form
}
return render(request, 'main/post.html', context_dict)
models.py
class Comment(models.Model):
def get_children(self):
if self.is_child:
return None
else:
return Comment.objects.filter(parent=self)
post.html
<h1>Comments/Questions</h1>
<form method="POST" action=''>{% csrf_token %}
{{ comment_form.as_p }}
<input type='submit' class='btn btn-default' value='Add comment'/>
</form>
<br/>
<hr/>
<table class='table'>
{% for comment in comments %}
<tr><td>{{ comment.get_comment }}
<br/><small>via {{ comment.user }} | {{ comment.timestamp|timesince }} ago </small>
{% if not comment.is_child %}
<ul>
{% for child in comment.get_children %}
<li>{{ child.get_comment }}
<small>via {{ child.user }}</small>
</li>
{% endfor %}
</ul>
<a href='#' class='reply_btn'>Reply</a>
<div class='reply_comment'>
<form method="POST" action=''>{% csrf_token %}
<input type='hidden' name='parent_id' value='{{ comment.id }}' />
{{ comment_form.as_p }}
<input type='submit' class='btn btn-default' value='Add reply'/>
</form>
</div>
{% endif %}
</td></tr>
{% endfor %}
</table>
</div>
и комментарий отображается в post.html и для этой страницы, точка зрения
def post(request, slug):
user = get_object_or_404(User,username__iexact=request.user)
try:
profile = MyProfile.objects.get(user_id=request.user.id)
# if it's a OneToOne field, you can do:
# profile = request.user.myprofile
except MyProfile.DoesNotExist:
profile = None
post = get_object_or_404(Post, slug=slug)
post.views += 1 # increment the number of views
post.save() # and save it
path = request.get_full_path()
comments = Comment.objects.filter(path=path)
#comments = post.comment_set.all()
comment_form = CommentForm(request.POST or None)
for c in comments:
c.get_children()
context_dict = {
'post' :post,
'profile' :profile,
'comments' : comments,
'comment_form':comment_form
}
return render(request, 'main/post.html', context_dict)
Я в основном следую за некоторым учебным пособием, и он не сделал recursetree, но его код работает .... hmm, где я должен использовать {% recursetree%}? – winixxee
'{% recursetree%}' является частью 'django-mptt'. Для комментариев приложение, это http://martinfitzpatrick.name/article/django-threaded-comments/ может помочь – v1k45
Извините, я думаю, что ввел вас в заблуждение, я не пытаюсь выполнить поток комментариев. Я просто хочу ответить на функцию комментария. не ответ после ответа после ответа ..... Я думаю, что в моем коде есть ошибка, но просто не могу понять, что ... – winixxee