如何在我的博客网站顶部显示最新帖子和评论?
Posted
技术标签:
【中文标题】如何在我的博客网站顶部显示最新帖子和评论?【英文标题】:How can I show newest posts and comments on the top in my blogging website? 【发布时间】:2021-01-18 19:06:55 【问题描述】:我已经成功地为 cmets 和帖子制作了模型,并且它们在网页上正确显示,但我希望首先显示最新帖子,并且 cmets 也是如此。
views.py:
from django.shortcuts import render, HttpResponse, redirect
from blog.models import Post, BlogComment
from django.contrib import messages
# Create your views here.
def blogHome(request):
allpost = Post.objects.all()
context = 'allposts': allpost
return render(request, 'blog/blogHome.html', context)
def blogPost(request, slug):
post = Post.objects.filter(slug=slug).first()
comments = BlogComment.objects.filter(post=post)
context = 'post': post, 'comments': comments
return render(request, 'blog/blogPost.html', context)
def postComment(request):
if request.method == 'POST':
comment = request.POST.get('comment')
user = request.user
postSno = request.POST.get("postSno")
post = Post.objects.get(sno=postSno)
comment = BlogComment(comment=comment, user=user, post=post)
comment.save()
messages.success(request, 'your comment has been added')
return redirect(f"/blog/post.slug")
这是我希望最先显示最新帖子的博客主页 blogHome.html:
% extends 'base.html' %
% block title % blogs % endblock title %
% block blogactive %active % endblock blogactive %
% block body %
<h2 class="text-center my-4">blogs by everythingcs</h2>
<div class="container">
% for post in allposts %
<div class="col-md-6">
<div class="row no-gutters border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative">
<div class="col p-4 d-flex flex-column position-static">
<strong class="d-inline-block mb-2 text-primary">by-post.author</strong>
<h3 class="mb-0">post.title</h3>
<div class="mb-1 text-muted">Nov 12</div>
<p class="card-text mb-auto">post.content|truncatechars:200</p>
<div class="my-2">
<a href="/blog/post.slug" role="button" class="btn btn-primary">More..</a>
</div>
</div>
</div>
</div>
% endfor %
</div>
% endblock body %
最后是 models.py 供进一步参考:
from django.db import models
from django.contrib.auth.models import User
from django.utils.timezone import now
# Create your models here.
class Post(models.Model):
sno = models.AutoField(primary_key=True)
title = models.CharField(max_length=50)
content = models.TextField()
author = models.CharField(max_length=50)
slug = models.SlugField(max_length=200)
timeStamp = models.DateTimeField(blank=True)
def __str__(self):
return self.title + " by " + self.author
class BlogComment(models.Model):
sno = models.AutoField(primary_key=True)
comment = models.TextField()
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True)
timestamp = models.DateTimeField(default=now)
def __str__(self):
return self.comment[0:13] + "..." + "by " + self.user.username
简而言之,我想按时间对我的博客文章和博客 cmets 进行排序,然后相应地显示它们。
【问题讨论】:
您可以保留像timeStamp
这样的 DB 字段,您可以在每次编辑帖子时更新该字段,并在显示所有帖子时保留 order_by
该字段。
看看这篇文章。 ***.com/questions/9834038/…。希望能解决你的问题
看看这篇文章。 ***.com/questions/9834038/…希望能解决你的问题
【参考方案1】:
您可以在对象的Meta
[Django-doc] 中指定默认的ordering
[Django-doc]:
class Post(models.Model):
sno = models.AutoField(primary_key=True)
title = models.CharField(max_length=50)
content = models.TextField()
author = models.CharField(max_length=50)
slug = models.SlugField(max_length=200)
timestamp = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-timestamp']
def __str__(self):
return f'self.title by self.author'
class BlogComment(models.Model):
sno = models.AutoField(primary_key=True)
comment = models.TextField()
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True)
timestamp = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-timestamp']
def __str__(self):
return f'self.comment[0:13]... by self.user.username'
或者您可以明确订购:
def blogHome(request):
allpost = Post.objects.order_by('-timestamp')
context = 'allposts': allpost
return render(request, 'blog/blogHome.html', context)
注意:通常Django模型中的字段名是用snake_case写的,而不是PerlCase,所以应该是:@ 987654332@ 而不是
。timeStamp
注意:通常使用
settings.AUTH_USER_MODEL
[Django-doc] 引用用户模型比直接使用User
model [Django-doc] 更好。更多信息可以查看referencing theUser
model section of the documentation。
注意:Django 的
DateTimeField
[Django-doc] 有一个auto_now_add=…
parameter [Django-doc] 使用时间戳。这将自动分配当前日期时间 创建对象时,将其标记为不可编辑(editable=False
),例如 默认情况下它不会出现在ModelForm
s 中。
【讨论】:
以上是关于如何在我的博客网站顶部显示最新帖子和评论?的主要内容,如果未能解决你的问题,请参考以下文章