我正在用django创建一个博客Web应用程序,我想在其中创建一个仅包含帖子标题的列表。 我想列出两个列表
在最新帖子中,我想列出最近创建的帖子的标题。最后创建的帖子应该在列表的第一位。简单
在“所有帖子”中,我想按升序列出所有帖子的标题。 我不确定该怎么做。
这是我的代码去.....
views.py
from django.shortcuts import render , redirect
from django.views.generic import TemplateView , ListView , DetailView
from .models import home_blog_model
from .forms import create_post
class home_view(ListView):
model = home_blog_model
template_name = "home.html"
context_object_name = "posts"
def detail_view(request , pk):
obj = home_blog_model.objects.get(id=pk)
context = {"obj":obj}
return render(request , "detail.html" , context)
def create_post_view(request):
if request.method == "POST":
form = create_post(request.POST)
if form.is_valid():
form.save()
return redirect("/home/")
else:
form = create_post()
return render(request , "create_post.html" , {"form":form})
home.html
{% extends "base.html" %}
{% load static %}
{% block body %}
<img src="{% static 'hori.jpg' %}" style="margin-top: 50px;margin-left: 250px;width: 60%">
<div class="row" style="margin-top: 40px;margin-left: 320px;margin-right: 20px">
{% for post in posts %}
<div class="col-sm-6 mb-4">
<div class="container" style="width: 300px;box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);transition: 0.3s;width: 100%;padding: 0px;">
<div class="card" style="height: 200px;padding: 12px;" onclick="location.href='{% url 'detail' post.id %}'">
<h2>{{ post.title }}</h2>
<div class="card-body">{{ post.summary }}</div>
</div>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
{% block head %}
<style>
.card:hover { box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2);}
</style>
{% endblock %}
models.py
from django.db import models
class home_blog_model(models.Model):
title = models.CharField(max_length=100)
summary = models.CharField(max_length=300)
content = models.TextField()
date = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
urls.py
from django.urls import path
from . import views
from django.contrib.auth.views import LoginView , LogoutView
urlpatterns = [
path("" , views.home_view.as_view() , name="blog-home"),
path("posts/<int:pk>/" , views.detail_view , name="detail"),
path("admin/login/" , LoginView.as_view(template_name="admin-login.html") , name="admin-login"),
path("admin/logout/" , LogoutView.as_view() , name="admin-logout"),
path("admin/post/create/" , views.create_post_view , name="create_post"),
]
提前谢谢。
答案 0 :(得分:0)
您可以使用dictsortreversed来发布最新帖子。例如:
# top 5 posts
{% for post in posts|dictsortreversed:"id"|slice:"5" %}
{{ post.title }}
{% endfor %}
通过这种方式,您可以在同一模板中以升序(例如代码的实现)和倒序发布帖子,而无需在视图中添加任何内容。添加了slice用于将列表切成5个对象。