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

时间:2018-09-04 00:39:08

标签: python django model

我正在尝试创建一个与每个主题分开的评论部分。由于某种原因,我创建的评论应用程序将显示每个主题的所有评论。例如,如果我要对主题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可以将其保存到该特定主题,但事实并非如此。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您可能想要

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