我正在尝试创建一个与每个主题分开的评论部分。出于某种原因,我创建的评论应用程序将显示每个主题的所有评论。例如,如果我要对主题 1 发表评论,同样的评论会出现在主题 2 上。主题1:评语:呵呵主题2:评语:呵呵评论应用程序:models.pyfrom django.db import modelsfrom django.conf import settingsfrom 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 formsfrom .models import Category, Topic, Entryfrom comments.models import Commentclass 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 Commentfrom .models import Category, Entry, Topicfrom .forms import CategoryForm, TopicForm, EntryForm, CommentFormdef 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 它将保存到该特定主题,但事实并非如此。任何帮助,将不胜感激。
添加回答
举报
0/150
提交
取消