为每篇文章 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)

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


胡说叔叔
浏览 164回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python