Qingquan-Li / blog

My Blog
https://Qingquan-Li.github.io/blog/
132 stars 16 forks source link

实现一个基于 Django 的动态加载数据的简单博客页面 #74

Open Qingquan-Li opened 6 years ago

Qingquan-Li commented 6 years ago

开发环境:

步骤:

  1. 创建模板:创建存放模板的文件夹,把 html 等静态文件放到这里
  2. 创建后台:创建超级管理员使用 Django 后台
  3. 引入数据:从 model 中找到数据引到 view 中,并且表现在 template 中
  4. 模板语言:模板标签 {% %} 、模板变量 {{ value }} 、模板过滤器 {{ value|filter }}

一、创建 Django project

  1. 创建一个文件夹,命名为 root(或其他命名),在终端中 cd 到文件 root 下
  2. 使用 django-admin 命令创建一个项目,命名为 firstsite(或其他命名): django-admin startproject firstsite
  3. 在 root/firstsite/manage.py 中第一行的 python 改为 python3.5(此项目开发环境使用的是 python3.5 ):#!/usr/bin/env python3.5

二、创建 Django App

每个 Django project 中可以有多个 Django apps,可以想成是类似模组的概念。

  1. 在 终端中 cd 到文件 root/firstsite 下,输入 python3.5 manage.py startapp firstapp 。注:manage.py 是 Django 提供的命令行工具
  2. 在 root/firstsite/firstsite/settings.py 中找到 INSTALLED_APPS ,在末尾添加刚创建的 app 名字(这里是 firstapp )

三、创建数据库

创建数据库后就可以看到 Django 网站的初始界面了。

  1. 合并数据库:在 终端中 cd 到文件 root/firstsite 下,运行以下 2 行命令合并数据库:1⃣ python3.5 manage.py makemigrations 2⃣ python3.5 manage.py migrate
  2. 运行服务器(数据库): python3.5 manage.py runserver 。访问 http://127.0.0.1:8000http://localhost:8000 即可看到 Django 网站的初始界面

四、把 HTML 、 CSS 、图片等文件放到模板中

  1. 在创建的 Django App(本文是firstapp)中创建2个文件夹:templates 、 static ,把 html 文件(这里是一个名为first_web_2.html的模板页面)放到 templates 文件夹中,把 css 文件(这里是semantic.css)和 images 文件等所有静态文件都放到 static 文件夹中

  2. 在 settings.py 中修改模板路径:为了让 Django 知道我们的模板在哪里,需要在 root/firstsite/setting.py 中修改 TEMPLATES 的 DIRS 如下:

    TEMPLATES = [
       {
           'BACKEND': 'django.template.backends.django.DjangoTemplates',
           # 'DIRS': [],
           # 修改模板路径,让Django知道模板放在哪里
           # 在父目录BASE_DIR中添加templates目录,目录中用 / 代替 \\。
           # stack overflow : You don't need to replace \\ by / since the Python os.path module know how to deal with this according to your current OS.
           'DIRS': [os.path.join(BASE_DIR, 'templates').replace('\\', '/')],
           'APP_DIRS': True,
           'OPTIONS': {
               'context_processors': [
                   'django.template.context_processors.debug',
                   'django.template.context_processors.request',
                   'django.contrib.auth.context_processors.auth',
                   'django.contrib.messages.context_processors.messages',
               ],
           },
       },
    ]
  3. 在 root/firstapp/templates 中的 HTML 文件中增加模板标签,为 CSS 文件、图片替换路径:

    # 在 html 首行添加静态文件标签,指引其找到并加载静态文件
    {% load staticfiles %}
    # css 路径,原:<link rel="stylesheet" href="css/semantic.css">
    href = "{% static 'css/semantic.css' %}"
    # 图片路径,原:background:url(images/star_banner.jpg)
    background:url({% static 'images/star_banner.jpg' %})

五、创建后台和超级管理员

Django 诞生于新闻网站的环境中,所以很重视内容管理,提供了管理后台,让使用者方便新增或修改网站内容。 这个管理后台,在 Django 中以内置app 的形式存在,叫做 Django Admin

  1. 设置管理员账户:在 终端中 cd 到文件 root/firstsite 下,输入 python3.5 manage.py createsuperuser

  2. 使用管理后台: python3.5 manage.py runserver 运行服务器,访问管理后台的登录页面 http://127.0.0.1:8000/admin ,使用第1步创建的 superuser 账号即可登录到后台页面 admin-login admin

  3. 在 root/firstsite/firstapp/admin.py添加数据项,这里添加 Article 项

    from django.contrib import admin
    from firstapp.models import Article # 增加 Article 的引入
    
    admin.site.register(Article)        # 增加数据项,并在models.py中定义文章的数据字段

    admin-article 可以点进去新增内容: admin-article-add

  4. 在 root/firstsite/firstapp/models.py 中添加 Article 数据字段 headlinecontent 。注意:为了让内容列表中能直接显示 headline 标题(而不是 Article object ),还需要在 root/firstsite/firstapp/models.py 中添加一个能直接显示标题的函数(对象==>str字符串)

    class Article(models.Model):
       headline = models.CharField(null=True, blank=True, max_length=500)
       content = models.TextField(null=True, blank=True)
       def __str__(self):
           return self.headline

    admin-article-object admin-article-str

  5. 合并数据库:在 终端中 cd 到文件 root/firstsite 下,运行以下 2 行命令合并数据库:1⃣ python3.5 manage.py makemigrations 2⃣ python3.5 manage.py migrate注:每次 model 层有改动都需要输入这 2 行合并数据库。 现在就可以到管理后台 http://localhost:8000/admin/firstapp/article/ 去添加文章了

  6. 附:清空数据库:python3 manage.py flush 将清空所有数据,包括清除超级管理员账户

六、在 View 中获取 Model 中的数据

from django.shortcuts import render
from firstapp.models import Article

# 在 View 中获取 Model 中的数据:创建视图函数
# 引用 models.py 里面写好的文章列表,然后去渲染文章列表
def index(request):
    # 使用数据库查询方法object.all()方法从Artic类的数据表中获取数据,放到变量artcle_list中
    article_list = Article.objects.all()
    # 创建一个空的字典
    context = {} 
    # 把数据装载进字典,字典的key-value建议相同
    context['article_list'] = article_list 
    # 使用render函数进行渲染,接收三个参数:请求、模板名称、上下文
    index_page = render(request, 'first_web_2.html', context)
    return index_page

七、在 Template 中增加动态内容

在 templates 文件夹下的 html 文件中,这里是 root/firstsite/firstapp/templates/first_web_2.html ,添加模板标签,让 first_web_2.html 的文章内容可以获取管理后台的数据

<div class="ui  vertical segment">
    <!-- 模板标签 -->
    {% for article in article_list %}
        <div class="ui container vertical segment">
            <a href="#">
                <h1 class="ui header">
                    <!-- 模板变量 -->
                    {{ article.headline }}
                </h1>
            </a>
            <i class="icon grey small unhide">10,000</i>
            <p>
                <!-- 模板过滤器 -->
                {{ article.content|truncatewords:100 }}
                <a href="#">
                    <i class="angle tiny double grey right icon">READMORE</i>
                </a>
            </p>
            <div class="ui mini tag label">
                life
            </div>
        </div>
    <!-- 记得增加for循环的结束标签 -->
    {% endfor %}  
</div>

八、在 URL 中分配网址

在 root/firstsite/firstsite/urls.py 中分配网址,让链接可以被访问:

"""firstsite URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from firstapp.views import index # 从firstapp包中的views模块中导入index视图函数

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index', index, name='index'), # 添加的代码
]

此时访问 http://127.0.0.1:8000/index/ 即可看到一个基于 Django 的动态加载数据的简单博客页面

bloger-index