gpt4 book ai didi

python - 如何在我的博客网站的顶部显示最新的帖子和评论?

转载 作者:行者123 更新时间:2023-12-04 08:48:37 25 4
gpt4 key购买 nike

我已经成功地为评论和帖子制作了模型,它们在网页上正确显示,但我希望最新的帖子首先显示,评论也是如此。
View .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 %}
最后是 模型.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
简而言之,我想按时间对我的博客文章和博客评论进行排序,然后相应地显示它们。

最佳答案

您可以指定默认值 ordering [Django-doc] Meta [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)

Note: normally the name of the fields in a Django model are written in snake_case, not PerlCase, so it should be: timestamp instead of timeStamp.



Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.



Note: Django's DateTimeField [Django-doc]has a auto_now_add=… parameter [Django-doc]to work with timestamps. This will automatically assign the current datetimewhen creating the object, and mark it as non-editable (editable=False), suchthat it does not appear in ModelForms by default.

关于python - 如何在我的博客网站的顶部显示最新的帖子和评论?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64182825/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com