DJango创建bolg的前台页面(精简版)NO.4

本文详细介绍了如何使用Django构建博客的前端页面,包括创建视图、定义URL路由、设置模板以及静态文件的配置。首先,定义了`post_list`和`post_detail`视图来展示文章列表和详情。接着,配置了URL路由,确保请求能正确映射到视图。在`templates`目录下创建了`blog`子目录,并为不同页面创建了对应的HTML模板。同时,更新了`models.py`以便获取文章的绝对URL。最后,配置了静态文件目录并完成了数据库迁移。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

构建视图
流程: 视图—URL—template

打开visws.py
from django.shortcuts import render,get_object_or_404
from .models import Post

添加标题视图

def post_list(request):
posts = Post.Published.all()
return render(request,‘blog/post/list.html’,{‘posts’: posts})

添加文章内容的视图
def post_detail(request, year, month, day, post, posts):
post = get_object_or_404(Post,slug=post,
status=‘published’,
publish__year = year,
publish__month= month,
publish__day = day)
return render(request,‘blog/post/detail.html’,{‘post’: post})

为视图制定URL
一个URL模式是由一个Python 正则表达,一个视图(view),一个全项目范围内的命名组成。
Django在运行中会遍历所有URL模式直到第一个匹配的请求URL才停止

在blog内新建一个urls.py
添加以下代码
from django.conf.urls import url
from . import views

urlpatterns = [
url(r’^$’, views.post_list,name=‘post_list’),
]

进入主 urls.py
里面代码为下
from django.conf.urls import url,include
from django.contrib import admin

urlpatterns = [
url(r’^admin/’, admin.site.urls),
url(r’^blog/’, include(‘blog.urls’, namespace=‘blog’)),
]

进入blog内的urls.py
里面代码为下
from django.conf.urls import url
from . import views

app_name = ‘blog’
urlpatterns = [
url(r’^$’, views.post_list,name=‘post_list’),
]

在blog下新建目录
templates----blog----post
static—css
在此目录下新建三个页面
detail.html list.html base.html

在blog下的urls.py中增加
url(r’(?P\d{4})/(?P\d{2})/(?P)\d{2}/’
r’(?P[-\w]+)/$’, views.post_detail,name=‘post_datail’)

在models.py中增加
from django.urls import reverse

再在下面增加一个函数
def get_absolute_usrl(self):
return reverse(‘blog:post_detail’,args=[self.publish.year,
self.publish.strftime(’%m’),
self.publish.strftime(’%d’),
self.slug])

创建模板
到settings.py 中增加一段代码
STATIC_ROOT = os.path.join(BASE_DIR,‘static’)

下载一个css 放css文件夹内 blog.css
编辑base.html

进入list.html 编辑

编辑betail.html

env中同步 python manage.py makemigrations
python manage.py migrate

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值