[英]Creating separate comment section per article 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.