python Django搭建简单的个人博客网站(三)

来源:互联网 发布:淘宝李茗汐怎么了 编辑:程序博客网 时间:2024/05/22 10:49

上节利用了Django admin搭建了博客的框架,现在手动完成简单的前后端逻辑

一.博客主页面

主页面包含文章标题列表(超链接)发表博客的按钮(超链接)

1.列表编写思路

取出数据库中所有文章对象

将文章对象们打包成列表,传递到前端

前端页面把文章以标题超链接的形式账户个列出

编辑view.py

# -*- coding: utf-8 -*-from __future__ import unicode_literalsfrom django.shortcuts import render  from django.http import HttpResponse  from .import models    def index(request):    aticles = models.Article.objects.all()    return render(request, 'blog/index.html', {'aticles': aticles})
编辑index.py

<!DOCTYPE html>  <html lang="en">  <head>    <meta charset="UTF-8">    <title>Title</title>  </head>  <body>   <h1> <a href=''>我的博客</a> </h1> {%for aticle in aticles%} <a href =''>{{aticle.title}}</a> <br/> {%endfor%}</body>  </html>  

二.博客文章页面

页面内容包括:标题、文章内容、修改文章按钮(超链接)

1.在APP目录下的templates/blog目录下新建article_page.html文件,并编辑

<!DOCTYPE html>  <html lang="en">  <head>    <meta charset="UTF-8">    <title>Aticle Page</title>  </head>  <body>   <h1>{{article.title}}</h1> <br/> <h3>{{article.content}}</h3> <br/><br/> <a href=''>编辑文章</a></body>  </html>  

2.编辑APP目录下的views.py,article_page中定义了参数article_id

# -*- coding: utf-8 -*-from __future__ import unicode_literalsfrom django.shortcuts import render  from django.http import HttpResponse  from .import models    def index(request):    aticles = models.Article.objects.all()    return render(request, 'blog/index.html', {'aticles': aticles})  def article_page(request,article_id):article = models.Article.objects.get(pk=article_id)return render(request,'blog/article_page.html',{'article':article})

3.编辑APP目录下的urls.py,正则匹配article_id

from django.conf.urls import urlfrom django.contrib import adminfrom . import viewsurlpatterns = [url(r'^$', views.index),url(r'^article/(?P<article_id>[0-9]+)$', views.article_page),]
4.在浏览器地址栏输入127.0.0.1/blog/article/1,其中1参数article_id,

5.Django中的超链接

HTML页面中a标签中href后面是目标地址

template中可以用{%url 'app_name:url_name' param%}\

其中app_name和url_name都在url中配置

url函数的名称参数

工程目录下,写在include()的第二个参数的位置,namesapce = 'blog'

应用下则写在url()的第三个参数位置,name=‘article_page’
主要取决于是否使用include引用了另外一个url配置文件


三.撰写的博客页面

-----------------------------------------------------------------待更--------------------------------------------