每篇文章Django创建单独的评论部分

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了每篇文章Django创建单独的评论部分相关的知识,希望对你有一定的参考价值。

我正在尝试创建一个与每个主题分开的注释部分。由于某种原因,我创建的评论应用程序将显示每个主题的所有评论。例如,如果我对主题1发表评论,相同的评论将出现在主题2上。

主题1:

评论:等等

主题2:

评论:等等

评论应用:models.py

from django.db import models
from django.conf import settings

from blogging_logs.models import Topic
# Create your models here.


class Comment(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, on_delete=models.CASCADE)
    topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
    content = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return str(self.content)

forms.py(在blogging_logs应用程序中)

from django import forms
from .models import Category, Topic, Entry
from comments.models import Comment

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ['content']
        labels = {'text': ''}
        widgets = {'text': forms.Textarea(attrs={'cols': 80})}

view.py(在blogging_logs应用程序中)

from comments.models import Comment
from .models import Category, Entry, Topic
from .forms import CategoryForm, TopicForm, EntryForm, CommentForm


def topic(request, entry_id):
    """Show entry for single topic"""
    topic = Topic.objects.get(id=entry_id)
    entries = topic.entry_set.all()
    comments = Comment.objects.all()

    if request.method != 'POST':
        # No comment submitted
        form = CommentForm()
    else:
        # Comment posted
        form = CommentForm(data=request.POST)
        if form.is_valid():
            new_comment = form.save(commit=False)
            new_comment.topic = topic
            new_comment.user = request.user
            new_comment.save()
            return HttpResponseRedirect(reverse('blogging_logs:topic', args=[entry_id]))

    context = {'topic': topic, 'entries': entries, 'comments': comments, 'form': form}
    return render(request, 'blogging_logs/topic.html', context)

topic.html

<h3> Comments Section </h3>
<form class="" action="{% url 'blogging_logs:topic' topic.id%}" method="post">
  {% csrf_token %}
  {{ form.as_p }}
  <button name='submit'> Add Comment </button>
</form>
  <div>
    {% for comment in comments %}
      {{ comment }}
      <p>{{comment.date_added|date:'M d, Y H:i' }}</p>
      <p>{{comment.user }}</p>
      <p>
        <a href="{% url 'blogging_logs:delete_comment' comment.id %}">Delete comment</a>
      </p>
    {% empty %}
      <p>no comments entered yet.</p>
    {% endfor %}
  </div>

我想通过抓住与主题相关联的entry_id,它将保存到该特定主题,但事实并非如此。任何帮助,将不胜感激。

答案

你可能想要

def topic(request, entry_id):
    """Show entry for single topic"""
    topic = Topic.objects.get(id=entry_id)
    entries = topic.entry_set.all()
    # This selects all comments, not what you want
    # comments = Comment.objects.all()
    # Instead you should select just the topic's comments
    comments = topic.comment_set.all()

请注意,这使用topic的反向外键关系。

https://docs.djangoproject.com/en/2.1/topics/db/queries/#related-objects

以上是关于每篇文章Django创建单独的评论部分的主要内容,如果未能解决你的问题,请参考以下文章

Django:使用 from 创建对象时出错

Django 博客开发教程 12 - 评论

Django 博客开发教程 12 - 评论

如何从我的带注释的 Django 查询中过滤/排除非活动评论?

在 Joomla 中以编程方式创建菜单层次结构

第六章.解决大问题