django框架学习五---构建列表、视图及视图模板

创建视图以显示列表

创建了两个视图,分别是post_list和post_detail

from django.shortcuts import render, get_object_or_404

#Create your views here.
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):
    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路径可将url映射到视图上,第二个路径是接受参数

from django.urls import path
from . import views

app_name = 'blog'

urlpatterns = [
    path('', views.post_list, name='post_list'),
    path('<int:year>/<int:month>/<int:day>/<slug:post>/',views.post_detail,name='post_detail')
]

另外,需要在主url路径中包含blog应用程序的url路径

path('blog/', include('blog.urls', namespace='blog')),

构建标准url

post_detail url针对Post对象构建标准url
1.向模型中添加get_absolute_url()方法
2.使用reverse(),通过对应的名称和参数构建url
3.使用get_absolute_url()即可链接到特定的帖子

def get_absolute_url(self):
    return reverse('blog:post_detail',args=[self.publish.year,self.publish.month,self.publish.day,self.slug])

创建视图模板

1.创建相应的目录

在这里插入图片描述

2.base.html(模板)

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>{% block title %}{% endblock %}</title>
   <link  rel="stylesheet" href="{% static "css/blog.css" %}">
</head>
<body>
   <div id="content">
       {% block content %}
       {% endblock %}
   </div>
   <div id="sidebar-content">
       <h2>My blog</h2>
       <p>This is my blog.</p>
   </div>

</body>
</html>

3.list.html

% extends "blog/base.html" %}

{% block title %}My blog{% endblock %}

{% block content %}
    <h1>My blog</h1>
    {% for post  in posts %}
        <h2>
            <a href="{{ post.get_absolute_url }}">
                {{ post.title }}
            </a>
        </h2>
        <p class="date">
            Published{{ post.publish }}by{{ post.author }}
        </p>
        {{ post.body|truncatewords:30|linebreaks }}
    {% endfor %}

{% endblock %}

4.detail.html

{% extends "blog/base.html" %}

{% block title %}{{ post.title }}{% endblock %}

{% block content %}
    <h1>{{ post.title }}</h1>
    <p class="date">
        Published{{ post.publish }}by{{ post.author }}
    </p>
    {{ post.body|linebreaks }}
{% endblock %}

还没解决的问题:HTML5中的sidebar用法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值