Blog with Django (Codemy.com) - 33 Comment Section
we need to associate new Comment model with Post model
add ordering!
when there are comments
No comments
add ordering!
1. models.py
class Comment(models.Model):
post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE)
name = models.CharField(max_length=250)
body = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '%s - %s' % (self.post.title, self.name)
on_delete=models.CASCADE
blog post gets deleted, comment gets automatically deleted.related_name="commemts"
this allow us to reference Comment models as comments def __str__(self):
return '%s - %s' % (self.post.title, self.name)
how it's shown in admin area
makemigrations, migrate
2. register at admin
from django.contrib import admin
from .models import Comment
admin.site.register(Comment)
3. add dummy data
at admin website, add a post.
4. templates
we can call comments through post model.
Even though model's name is 'Comment'(singular), we call it as 'comments'(plural) because we set related_name to 'comments' related_name="commemts"
add_posts.html<!--Comment-->
<hr>
<h2>Comment</h2>
{% if not post.comments.all %}
No Comments yet...<a href="#">Add one
{% else %}
{% for comment in post.comments.all %}
<strong>{{ comment.name }} - {{ comment.date_added }}</strong> <br>
<br>
{{ comment.body }}
<br>
<hr>
{% endfor %}
{% endif %}
Results
class Comment(models.Model):
post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE)
name = models.CharField(max_length=250)
body = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '%s - %s' % (self.post.title, self.name)
def __str__(self):
return '%s - %s' % (self.post.title, self.name)
from django.contrib import admin
from .models import Comment
admin.site.register(Comment)
<!--Comment-->
<hr>
<h2>Comment</h2>
{% if not post.comments.all %}
No Comments yet...<a href="#">Add one
{% else %}
{% for comment in post.comments.all %}
<strong>{{ comment.name }} - {{ comment.date_added }}</strong> <br>
<br>
{{ comment.body }}
<br>
<hr>
{% endfor %}
{% endif %}
Reference
この問題について(Blog with Django (Codemy.com) - 33 Comment Section), 我々は、より多くの情報をここで見つけました https://velog.io/@daylee/Blog-with-Django-Codemy.com-33-34-Comment-Sectionテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol