美文网首页
Django 学习

Django 学习

作者: 沧海一粟谦 | 来源:发表于2018-06-27 09:18 被阅读7次
    Star Trek

    Window 下安装 Django

    如果你还未安装Python环境需要先下载Python安装包。

    1、Python 下载地址:https://www.python.org/downloads/

    2、Django 下载地址:https://www.djangoproject.com/download/

    安装完成后你需要设置Python环境变量。 右击计算机->属性->高级->环境变量->修改系统变量path,添加Python安装地址

    Django 安装(pip install django)

    下载 Django 压缩包,解压并和Python安装目录放在同一个根目录,进入 Django 目录,执行python setup.py install,然后开始安装,Django将要被安装到 Python 的 Lib下 site-packages

    然后是配置环境变量,将这几个目录添加到系统环境变量中: C:\Python33\Lib\site-packages\django;C:\Python33\Scripts

    检查是否安装成功

    >>> import django
    >>> django.get_version()
    

    创建第一个项目

    django-admin startproject HelloWorld
    

    创建完成后我们可以查看下项目的目录结构:

    cd HelloWorld/
    .
    |-- HelloWorld
    |   |-- __init__.py
    |   |-- settings.py
    |   |-- urls.py
    |   `-- wsgi.py
    `-- manage.py
    

    目录说明:

    • HelloWorld: 项目的容器。
    • init.py: 一个空文件,告诉 Python 该目录是一个 Python 包。
    • settings.py: 该 Django 项目的设置/配置。
    • urls.py: 该 Django 项目的 URL 声明; 一份由 Django 驱动的网站"目录"。
    • wsgi.py: 一个 WSGI 兼容的 Web 服务器的入口,以便运行你的项目。
    • manage.py: 一个实用的命令行工具,可让你以各种方式与该 Django 项目进行交互。

    进入 HelloWorld 目录输入以下命令,启动服务器:

    python manage.py runserver 0.0.0.0:8000
    

    0.0.0.0 让其它电脑可连接到开发服务器,8000 为端口号。如果不说明,那么端口号默认为 8000。在浏览器输入你服务器的ip及端口号

    视图和 URL 配置

    在 HelloWorld 目录下的 HelloWorld 目录新建一个 views.py 文件,并输入代码:

    from django.http import HttpResponse
    from django.shortcuts import render
     
    def hello(request):
        context ={}
        context["name"] = "C罗"
        context["age"] = "18"
    
        return render(request,'hello.html',context)
    

    绑定 URL 与视图函数:

    from django.urls import path
    from . import views
    from django.conf.urls import url
     
    urlpatterns = [
        url(r'^$',views.hello),
    ]
    

    在 HelloWorld 目录下创建 templates 存放页面 hello.html

    <!DOCTYPE html>
    <html>
    <head>
        <title>python之禅</title>
    </head>
    <body>
        <h1>人生苦短,我选python</h1>
        <h2>姓名:{{name}}</h2>
        <h2>年龄:{{age}}</h2>
        <h2><a href="/add">添加</a></h2>
        <h2><a href="/list">列表</a></h2>
        <h2><a href="/img">图片</a></h2>
    </body>
    </html>
    

    在 setting.py 中 配置 templates



    测试


    注意:项目中如果代码有改动,服务器会自动监测代码的改动并自动重新载入,所以如果你已经启动了服务器则不需手动重启。

    显示上一章爬取的图片

    在 template 同级新建 static/img,把图片复制进去,并在 setting.py 中配置静态文件

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

    urls.py

    urlpatterns = [
        url(r'^$',views.hello),
            url(r'^img$',views.img_list),
    ]
    

    views.py

    def img_list(request):
        context ={}
        img_list = os.listdir("D:\\Sublime\\workplace\\day3\\django\\HelloWorld\\static\\img")
        context["img_list"] = img_list
    
        return render(request,'img_list.html',context)
    

    img_list.html

    <!DOCTYPE html>
    <html>
    <head>
        <title>图片列表</title>
    </head>
    <body>
    {% for img_name in img_list %}
    <img src="/static/img/{{ img_name }}" alt="some_text">
    {% endfor %}
    </body>
    </html>
    

    增删改查

    views.py

    from django.http import HttpResponse
    from django.shortcuts import render
    import os
    import json
    import random
    
    def add_user(request):
        context ={}
        context["name"] = "梅西"
        context["age"] = 24
    
        return render(request,'add_user.html',context)
    
    
    def add_one(request):
        name = request.POST["name"]
        age = request.POST["age"]
    
        context ={}
        context["name"] = name
        context["age"] = age
    
        user_list = []
        user_dict = {}
        user_dict["id"] = random.randint(0,99999)
        user_dict["name"] = name
        user_dict["age"] = age
    
        with open("d:\\result.json",'r') as rf:
            result_str = rf.read()
    
        user_list = json.loads(result_str)
        user_list.append(user_dict)
    
        json_str = json.dumps(user_list)
        with open("d:\\result.json",'w') as f:
            f.write(json_str)
    
        context["user_list"] = user_list
        return render(request,'detail.html',context)
    
    def list(request):
        context ={}
        users = []
    #   users.append("user1")
        user1 = {"id":1,"name":"梅西 ","age":30,"value":"1.2亿"}
        user2 = {"id":2,"name":"C罗 ","age":32,"value":"8千万"}
        user3 = {"id":3,"name":"内马尔 ","age":28,"value":"6千万"}
        users.append(user1)
        users.append(user2)
        users.append(user3)
        context["users"] = users
    
        return render(request,'list.html',context)
    
    def remove(request):
        user_list = []
        context ={}
        user_id = request.GET["id"]
        print("删除数据的id是:%s" % user_id )
    
        with open("d:\\result.json",'r') as rf:
            result_str = rf.read()
    
        user_list = json.loads(result_str)
        i = -1
        for item in user_list:
            i+=1
            if item["id"] == int(user_id):
                del user_list[i]
    
        json_str = json.dumps(user_list)
        with open("d:\\result.json",'w') as wf:
            wf.write(json_str)
    
        context["user_list"] = user_list
    
        return render(request,'detail.html',context)
    
    def edit(request):
        context = {}
        user_id = request.GET["id"]
    
        with open("d:\\result.json",'r') as rf:
            result_str = rf.read()
    
        old_user_list = json.loads(result_str)
        i = -1
        for item in old_user_list:
            i+=1
            if item["id"] == int(user_id):
                new_user_list = old_user_list[i]
        print(new_user_list)
        context["new_user_list"] = new_user_list
    
        return render(request,'edit.html',context)
    
    def doedit(request):
        context ={}
        user_id = request.POST["id"]
        name = request.POST["name"]
        age = request.POST["age"]
        
        with open("d:\\result.json",'r') as rf:
            result_str = rf.read()
    
        user_list = json.loads(result_str)
        i = -1
        for item in user_list:
            i+=1
            if item["id"] == int(user_id):
                user_list[i]["name"] = name
                user_list[i]["age"] = age
                print(user_list[i]["name"])
    
        json_str = json.dumps(user_list)
        with open("d:\\result.json",'w') as wf:
            wf.write(json_str)
    
        context["user_list"] = user_list
        return render(request,'detail.html',context)
    

    urls.py

    urlpatterns = [
        url(r'^$',views.hello),
        url(r'^add$',views.add_user),
        url(r'^add_one$',views.add_one),
        url(r'^list$',views.list),
        url(r'^remove$',views.remove),
        url(r'^edit$',views.edit),
        url(r'^doedit$',views.doedit),
        url(r'^find$',views.find),
        url(r'^img$',views.img_list),
    ]
    

    add_user.html

    <!DOCTYPE html>
    <html>
    <head>
        <title>添加</title>
    </head>
    <body>
    
        <h2>姓名:{{ name }}</h2>
        <h2>年龄:{{ age }}</h2>
    
        <form action="/add_one" method="post" name="form1">
           {% csrf_token %}
            姓名:<input type="text" name="name" value=""/>
            <br/><br/>
            年龄:<input type="text" name="age" value=""/>
            <br/><br/>
            <input type="submit" name="" value="提交" />
        </form>
    </body>
    </html>
    

    detail.html

    <!DOCTYPE html>
    <html>
    <head>
        <title>详情</title>
    </head>
    <body>
    <img src="/static/img/scene.png" alt="some_text">
    <h2>姓名:{{ name }}</h2>
    <h2>年龄:{{ age }}</h2>
    <table border="1">
            <tr>
                <th>id</th>
                <th>姓名</th>
                <th>年龄</th>
            </tr>
            
            {% for user in user_list %}
                <tr>
                    <td>{{ user.id }}</td>
                    <td>{{ user.name }}</td>
                    <td>{{ user.age }}</td>
                    <td><a href="/remove?id={{user.id}}">删除</a></td>
                    <td><a href="/edit?id={{user.id}}">修改</a></td>
                </tr>
            {% endfor %}
        </table>
    </body>
    </html>
    

    edit,html

    <!DOCTYPE html>
    <html>
    <head>
        <title>编辑</title>
    </head>
    <body>
        <form action="/doedit" method="post" name="form2">
           {% csrf_token %}
            姓名:<input type="text" name="name" value="{{ new_user_list.name }}"/>
            <br/><br/>
            年龄:<input type="text" name="age" value="{{ new_user_list.age }}"/>
            <br/><br/>
            <input type="hidden" name="id" value="{{ new_user_list.id }}" >
            <input type="submit" name="" value="提交" />
        </form>
    
    </body>
    </html>
    

    相关文章

      网友评论

          本文标题:Django 学习

          本文链接:https://www.haomeiwen.com/subject/vramdftx.html