我正在嘗試創建一個與每個主題分開的評論部分。出于某種原因,我創建的評論應用程序將顯示每個主題的所有評論。例如,如果我要對主題 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
提交
取消