​ 讲解的很简洁!

概述:主要参考上面视频进行学习,此处是部分代码笔记. 展示github 用户信息.

工具

  • vscode;
  • git bash;
  • chrome;
  • Django3.0
  • boostrap4.0

目录结构如下

image.png

上传到我的github :

echo "# Django_demo" >> README.md
git init
git add README.md
git add .
git commit -m "first commit"
git remote add origin https://github.com/caokai001/Django_demo.git
git push -u origin master
Django 架构
2020年1月27日18:06:48


1.成果展示

简书无法加载gif,点击查看gif 效果

2.python 安装

2020年1月21日21:37:09
### 新建文件夹
mkdir 2020-1
cd 2020-1
### 检查python版本(高版本的Django 不支持python2.x)
16926@DESKTOP-NC9OOR3 MINGW64 ~/Desktop/2020-1
$ python -V
Python 3.6.4 :: Anaconda, Inc.

3.虚拟环境安装使用

### 查询base环境中存在哪些安装包(为了环境隔离,最好建立新的py环境)
$ pip freeze
... 好多包

### pip 加速下载
$ pip install -i https://pypi.douban.com/simple/ virtualenv
Collecting virtualenv
  Downloading https://files.pythonhosted.org/packages/05/f1/2e07e8ca50e047b9cc9ad56cf4291f4e041fa73207d000a095fe478abf84/virtualenv-16.7.9-py2.py3-none-any.whl (3.4MB)

### 建立虚拟环境
$ virtualenv.exe .
Using base prefix 'c:\\users\\16926\\anaconda3'
New python executable in C:\Users\16926\Desktop\2020-1\Scripts\python.exe
Installing setuptools, pip, wheel...
done.

### 激活虚拟环境
16926@DESKTOP-NC9OOR3 MINGW64 ~/Desktop/2020-1
$ source ./Scripts/activate

### 检查虚拟环境中包
(2020-1)
16926@DESKTOP-NC9OOR3 MINGW64 ~/Desktop/2020-1
$ pip freeze
(空)

4.安装Django

### 安装最新版django
(2020-1)
16926@DESKTOP-NC9OOR3 MINGW64 ~/Desktop/2020-1
$ pip install -i https://pypi.douban.com/simple/ django
Installing collected packages: asgiref, sqlparse, pytz, django
Successfully installed asgiref-3.2.3 django-3.0.2 pytz-2019.3 sqlparse-0.3.0

### 虚拟环境包
(2020-1)
16926@DESKTOP-NC9OOR3 MINGW64 ~/Desktop/2020-1
$ pip freeze
asgiref==3.2.3
Django==3.0.2
pytz==2019.3
sqlparse==0.3.0

5.启动Django 小程序

### 默认环境及其路径,下面将省略
(2020-1)
16926@DESKTOP-NC9OOR3 MINGW64 ~/Desktop/2020-1

### 建立mysite 项目
$ django-admin.exe startproject mysite

### 进入mysite项目
$ cd mysite/

### 运行实例app
(2020-1)
16926@DESKTOP-NC9OOR3 MINGW64 ~/Desktop/2020-1/mysite
$ python manage.py runserver

进入浏览器: http://127.0.0.1:8000/

2020年1月21日23:36:48
2020年1月21日23:39:44

6.配置路由urls

### 创建一个app (misterwu)
(2020-1)
16926@DESKTOP-NC9OOR3 MINGW64 ~/Desktop/2020-1/mysite
$ python manage.py startapp misterwu

### 修改mysite目录下setting.py内容
# tips:将创建的app 与project 关联,告诉Django 这是一个app
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    "misterwu",
]

### 修改mysite目录下urls.py ,解析网址和视图函数关系

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('misterwu.urls')),  # 需要新建misterwu目录下urls.py文件
]

### 新建misterwu目录下urls.py文件
from django.urls import path

urlpatterns = [
    # 先省略
]

7.展示出html 页面

### 新建misterwu目录下urls.py文件
from django.urls import path
from . import views

urlpatterns = [
    path('',views.home,name="home") # 需要新建views.py 下home 方法
]

### 新建misterwu目录下views.py文件
from django.shortcuts import render

# Create your views here.
def home(request):
    return render(request,"home.html",{})  # 需要新建misterwu/templates目录下home.html文件
  
### 新建misterwu/templates目录下home.html文件
<h1>Hello world</h1>

进入浏览器: http://127.0.0.1:8000/

2020年1月22日00:09:39

梳理一下思路:

urls.py
path('',include('misterwu.urls'))
views.py
path('',views.home,name="home")
home.html
def home(request):
    return render(request,"home.html",{})  # 需要新建misterwu目录下home.html文件
Hello world
<h1>Hello world</h1>

8.创建公共html 模板

block
<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

    <title>Hello, world!</title>
  </head>
  <body>
    {% block content %}
    {% endblock %}


    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.4.1/dist/jquery.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
  </body>
</html>

8.2 修改home.html

用extends 加载base.html模板.有点类似继承关系.

{% extends 'base.html' %}

{% block content %}
    <h1>Hello world</h1>
    <p>测试是否可以看到我!</p>
{% endblock %}

9.添加导航信息

1.<div class="container">...</div> : 将信息居中显示

对base.html 进行修改,添加导航条

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

    <title>米斯特吴</title>
  </head>
  <body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">   <!-- dark/light 修改nav背景 -->
      <a class="navbar-brand" href="#">米斯特吴</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
    
      <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav mr-auto">
          <li class="nav-item">
            <a class="nav-link" href="#">Link</a>
          </li>
        </ul>
        <form class="form-inline my-2 my-lg-0">
          <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
          <button class="btn btn-outline-success my-2 my-sm-0" type="submit">搜索</button>
        </form>
      </div>
    </nav>




  </br>
    <div class="container">
    {% block content %}
    {% endblock %}
    </div>

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.4.1/dist/jquery.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
  </body>
</html>

效果如下:

2020年1月22日00:57:34

10.Github API 接口介绍

image.png
image.png

11.接口请求和解析

下载 requests 模块

(2020-1)
16926@DESKTOP-NC9OOR3 MINGW64 ~/Desktop/2020-1
$ pip install -i https://pypi.douban.com/simple/ requests

修改misterwu目录下,views.py 请求函数

from django.shortcuts import render


# Create your views here.
def home(request):
    import requests
    import json
    api_request = requests.get("http://api.github.com/users?since=0")
    api = json.loads(api_request.content)

    return render(request, "home.html",
                  {"api": api})  # 需要新建misterwu目录下home.html文件

修改home.html ,添加api 变量

{% extends 'base.html' %}

{% block content %}
    <h1>Hello world</h1>
    <p>测试是否可以看到我!</p>
{% endblock %}

运行结果如下: python manage.py runserver

image.png

12.更好的展示数据信息

bs4 card 渲染card 形式

home.html
{% block content %}
    <h1>Hello world</h1>
    <p>测试是否可以看到我!</p>

    <div class="container">
        <div class="row">
            {% for x in api %}
            <div class="col-sm">
                <div class="card" style="width: 18rem;">
                    <img class="card-img-top" src="{{x.avatar_url}}" alt="...">
                    <div class="card-body">
                        <h5 class="card-title">{{x.login}}</h5>
                        <p class="card-text">{{x.login}}的github</p>
                        <a href="{{x.html_url}}" class="btn btn-primary">访问</a>
                    </div>
                </div>
                <br>
                <br>
            </div>
            {% endfor %}
        </div>
    </div>

    <p>{{api}}</p>
{% endblock %}

效果如下:

2020年1月22日02:06:09

13.搜索页面跳转

1.添加user/ 路由, 实现路由访问 http://localhost:8000/user/

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('misterwu.urls')),
]
  • 修改misterwu目录下urls.py
from django.urls import path
from . import views

urlpatterns = [path('', views.home, name="home"),
               path('user/', views.user, name="user")]
  • 修改misterwu目录下view.py
def user(request):
    return render(request, 'user.html', {})
{% extends 'base.html' %}

{% block content %}

    <h1>Hello world!</h1>
    <p>测试是否可以看到我!</p>

{% endblock %}
2020年1月26日14:53:49
search

修改misterwu/template 目录下base from 表单,链接到user/路由函数上

**1.method="POST" action="{% url 'user' %}" **

**2.{{% csrf_token % }} **

3.将input 命名为user : name= "user"

<form class="form-inline my-2 my-lg-0" method="POST" action="{% url 'user' %}">
    {% csrf_token %}
          <input class="form-control mr-sm-2" name= "user" type="search" placeholder="Search" aria-label="Search">
          <button class="btn btn-outline-success my-2 my-sm-0" type="submit">搜索</button>
        </form>

测试结果:

image.png
user/
2020年1月26日14:53:49

3.点击search ,捕获输入内容

修改misterwu 目录下views.py : 捕获表单input,并且传递给user.html

def user(request):
    user = request.POST["user"]
    return render(request, 'user.html', {'user': user})
user.html
{% extends 'base.html' %}

{% block content %}
    <h1>Hello {{user}}!</h1>
    <p>测试是否可以看到我!</p>
{% endblock %}
kcaosearch
2020年1月26日15:55:24
search
2020年1月26日16:38:58

思路:

米斯特吴查询
  1. 修改base.html . 对米斯特吴,link 两个link,添加链接
<a class="navbar-brand" href="{% url 'home' %}">米斯特吴</a>

<a class="nav-link" href="{% url 'user' %}">查询</a>
  1. 对views.py 进行修改
from django.shortcuts import render


# Create your views here.
def home(request):
    import requests
    import json
    api_request = requests.get("http://api.github.com/users?since=0")
    api = json.loads(api_request.content)

    return render(request, "home.html",
                  {"api": api})  # 需要新建misterwu目录下home.html文件


def user(request):
    if request.method == "POST":
        user = request.POST['user']
        return render(request, 'user.html', {'user': user})
    else:
        notfound = "请在输入框中输入您要查询的用户..."
        return render(request, 'user.html', {'notfound': notfound})

3.对 user.html 进行修改。(ps: Django 自带的模板语言,类似python 语法)

{% extends 'base.html' %}

{% block content %}
    <!-- <h1>Hello {{user}}!</h1>
    <p>测试是否可以看到我!</p> -->
    {% if notfound %}
        <h2>{{notfound}}</h2>
    {% else %}
        <h1>Hello {{user}}!</h1>
    {%endif%}

{% endblock %}

对两种请求方式进行判断,展示不同的信息

进一步完善search 功能,(通过表单提交,点击search 返回的结果)

  • misterwu/templates 目录下base 修改如下:
{% extends 'base.html' %}

{% block content %}
    <!-- <h1>Hello {{user}}!</h1>
    <p>测试是否可以看到我!</p> -->
    {% if notfound %}
        <h2>{{notfound}}</h2>
    {% else %}
        <div class="col-sm">
            <div class="card" style="width: 18rem;">
                <img class="card-img-top" src="{{username.avatar_url}}" alt="...">
                <div class="card-body">
                    <h5 class="card-title">{{username.login}}</h5>
                    <p class="card-text">location: {{username.location}}的github</p>
                    <p class="card-text">public_repos: {{username.public_repos}}的github</p>
                    <p class="card-text">public_gists: {{username.public_gists}}的github</p>
                    <p class="card-text">followers: {{username.followers}}的github</p>
                    <p class="card-text">following: {{username.following}}的github</p>
                    <p class="card-text">created_at: {{username.created_at}}的github</p>
                    <p class="card-text">updated_at: {{username.updated_at}}的github</p>
                </div>
            </div>
            <br>
            <br>
        </div>
        <h1>Hello {{user}}!</h1>
    {%endif%}

{% endblock %}

运行效果:

2020年1月27日01:24:58

参考资料: