Django项目中使用BootStrap


注:刚开始学Python,很多东西都不懂,参考了很多博主的博客,记录下来以防自己忘记。若是有错误的地方,欢迎大家指正,谢谢。

1.下载Boostrap组件

下载链接:https://v3.bootcss.com/getting-started/#download
在项目根目录下创建static目录,把下载后解压的文件复制到static中
在这里插入图片描述

2.修改配置文件setting.py

在setting.py中查找到’STATIC_CRL’,再下面输入以下代码配置路径

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

注:在使用时先检查setting.py最前面有没有import os

3.修改views.py文件

代码如下:这里是读取了数据库的数据,若是不理解,可以查看https://blog.csdn.net/m0_48901291/article/details/118146686

from django.shortcuts import render
from django.db import connection
def lists(request):
    mycursor = connection.cursor();
    mycursor.execute('select * from student')
    rows = mycursor.fetchall()
    list_content = {
        "students": rows
    }
    return render(request, 'list.html', context=list_content)

4.在页面进行展示

在templates目录下创建base.html文件和list.html文件。
base.html代码:

<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>{% block title %}{% endblock %}</title>
    <link href="/static/bootstrap/css/bootstrap.css" rel="stylesheet">

</head>
<body>
    <div class="container">
        <h2>学生信息</h2>
        <hr>
        {% block mainbody %}

        {% endblock mainbody %}
    </div>

<!--JQuerry (necessary for Bootstrap's Javascript plugins)-->
<script src="/static/bootstrap/js/jquery.min.js"></script>
<script src="/static/bootstrap/js/bootstrap.min.js"></script>
</body>
</html>

list.html代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{% extends 'base.html'%}
{% block mainbody %}
<table class="table table-bordered table-hover">
    <tr>
        <th>序号</th>
        <th>ID</th>
        <th>姓名</th>
        <th>年龄</th>
    </tr>
    {% for student in students %}
    <tr>
        <td>{{forloop.counter}}</td>
        <td>{{student.0}}</td>
        <td>{{student.1}}</td>
        <td>{{student.2}}</td>
    </tr>
{% endfor %}
</table>
{% endblock mainbody %}
</body>
</html>

最终结果为:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值