Django

Posted Manger

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django相关的知识,希望对你有一定的参考价值。

1、Django请求的生命周期
        路由系统 -> 视图函数(获取模板+数据-->渲染) -> 字符串返回给用户
 
2、路由系统
        /index/                ->  函数或类.as_view()
        /detail/(\\d+)          ->  函数(参数) 或 类.as_view()(参数)
        /detail/(?P<nid>\\d+)   ->  函数(参数) 或 类.as_view()(参数)
        /detail/               ->  include("app01.urls")
        /detail/    name=\'a1\'  ->  include("app01.urls")
                               - 视图中:reverse
                               - 模板中:{% url "a1" %}
 
3、视图
    FBV:函数
        def index(request,*args,**kwargs):
            ..
 
    CBV:类
        class Home(views.View):
 
            def get(self,reqeust,*args,**kwargs):
                ..
 
    获取用户请求中的数据:
        request.POST.get
        request.GET.get
        reqeust.FILES.get()
 
        # checkbox,
        ........getlist()
 
        request.path_info
 
 
        文件对象 = reqeust.FILES.get()
        文件对象.name
        文件对象.size
        文件对象.chunks()
 
        # <form 特殊的设置></form>
 
    给用户返回数据:
        render(request, "模板的文件的路径", {\'k1\': [1,2,3,4],"k2": {\'name\': \'张扬\',\'age\': 73}})
        redirect("URL")
        HttpResponse(字符串)
 
4、模板语言
        render(request, "模板的文件的路径", {\'obj\': 1234, \'k1\': [1,2,3,4],"k2": {\'name\': \'张扬\',\'age\': 73}})
 
    <html>
 
    <body>
        <h1> {{ obj }} </h1>
        <h1> {{ k1.3 }} </h1>
        <h1> {{ k2.name }} </h1>
        {% for i in k1 %}
            <p> {{ i }} </p>
        {% endfor %}
 
        {% for row in k2.keys %}
            {{ row }}
        {% endfor %}
 
        {% for row in k2.values %}
            {{ row }}
        {% endfor %}
 
        {% for k,v in k2.items %}
            {{ k }} - {{v}}
        {% endfor %}
 
    </body>
    </html>
 
5、ORM
    a. 创建类和字段
        class User(models.Model):
            age = models.IntergerFiled()
            name = models.CharField(max_length=10)#字符长度
 
        Python manage.py makemigrations
        python manage.py migrate
 
        # settings.py 注册APP
 
    b. 操作
        增
            models.User.objects.create(name=\'qianxiaohu\',age=18)
            dic = {\'name\': \'xx\', \'age\': 19}
            models.User.objects.create(**dic)
 
 
            obj = models.User(name=\'qianxiaohu\',age=18)
            obj.save()
        删
            models.User.objects.filter(id=1).delete()
        改
            models.User.objects.filter(id__gt=1).update(name=\'alex\',age=84)
            dic = {\'name\': \'xx\', \'age\': 19}
            models.User.objects.filter(id__gt=1).update(**dic)
        查
            models.User.objects.filter(id=1,name=\'root\')
            models.User.objects.filter(id__gt=1,name=\'root\')
            models.User.objects.filter(id__lt=1)
            models.User.objects.filter(id__gte=1)
            models.User.objects.filter(id__lte=1)
 
            models.User.objects.filter(id=1,name=\'root\')
            dic = {\'name\': \'xx\', \'age__gt\': 19}
            models.User.objects.filter(**dic)
 
6、获取单表单数据的三种方式(views.py )
          def business(request):
            v1 = models.Business.objects.all()
            # QuerySet ,内部元素都是对象
 
            v2 = models.Business.objects.all().values(\'id\',\'caption\')
            # QuerySet ,内部元素都是字典
            
            v3 = models.Business.objects.all().values_list(\'id\',\'caption\')
            # QuerySet ,内部元素都是元组
 
             return render(request, \'business.html\', {\'v1\': v1,\'v2\': v2, \'v3\': v3})
 
            特别注意
            # 获取到的一个对象,如果不存在就报错
            models.Business.objects.get(id=1)
            但可以用下面的方式来获取对象
            对象或者None = models.Business.objects.filter(id=1).first()
 
 代码示例如下:
from django.shortcuts import render, HttpResponse, redirect
from  app01 import models
import json


# Create your views here.
def business(request):
    v1 = models.Business.objects.all()

    v2 = models.Business.objects.all().values(\'id\', \'caption\', \'code\')

    v3 = models.Business.objects.all().values_list(\'id\', \'caption\', \'code\')

    return render(request, \'business.html\', {\'v1\': v1, \'v2\': v2, \'v3\': v3})


def host(request):
    if request.method == "GET":
        v1 = models.Host.objects.filter(nid__gt=0)
        v2 = models.Host.objects.filter(nid__gt=0).values(\'nid\', \'hostname\', \'b_id\', \'b__caption\')
        v3 = models.Host.objects.filter(nid__gt=0).values_list(\'nid\', \'hostname\', \'b_id\', \'b__caption\')

        b_list = models.Business.objects.all()

        return render(request, \'host.html\', {\'v1\': v1, \'v2\': v2, \'v3\': v3, \'b_list\': b_list})

    elif request.method == "POST":

        h = request.POST.get(\'hostname\')
        i = request.POST.get(\'ip\')
        p = request.POST.get(\'port\')
        b = request.POST.get(\'b_id\')
        models.Host.objects.create(hostname=h,
                                   ip=i,
                                   port=p,
                                   b_id=b
                                   )
        return redirect(\'/host\')


def test_ajax(request):

    ret = {\'status\': True, \'error\': None, \'data\': None}
    try:
        h = request.POST.get(\'hostname\')
        i = request.POST.get(\'ip\')
        p = request.POST.get(\'port\')
        b = request.POST.get(\'b_id\')
        if h and len(h) > 5:
            models.Host.objects.create(hostname=h,
                                           ip=i,
                                           port=p,
                                           b_id=b)
        else:
            ret[\'status\'] = False
            ret[\'error\'] = "太短了"
    except Exception as e:
        ret[\'status\'] = False
        ret[\'error\'] = \'请求错误\'
    return HttpResponse(json.dumps(ret))
views.py
from django.db import models

# Create your models here.

class Business(models.Model):
    caption = models.CharField(max_length=32)
    code = models.CharField(max_length=32)

class Host(models.Model):

    nid = models.AutoField(primary_key=True)
    hostname = models.CharField(max_length=32,db_index=True)
    ip = models.GenericIPAddressField(db_index=True)
    port = models.IntegerField()
    b = models.ForeignKey(to="Business",to_field=\'id\')
models.py
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
        .hide {
            display: none;
        }

        .shade {
            position: fixed;
            top: 0;
            right: 0;
            left: 0;
            bottom: 0;
            background: black;
            opacity: 0.6;
            z-index: 100;
        }

        .add-modal, .edit-modal, .delete-modal {
            position: fixed;
            height: 300px;
            width: 400px;
            top: 100px;
            left: 50%;
            z-index: 101;
            border: 1px solid red;
            background: white;
            margin-left: -200px;
        }
    </style>
</head>
<body>
<h1>主机列表(对象)</h1>
<div>
    <input id="add_host" type="button" value="添加"/>
</div>
<table border="1">
    <thead>
    <tr>
        <th>序号</th>
        <th>主机名</th>
        <th>IP</th>
        <th>端口</th>
        <th>业务线名称</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbody>

    {% for row in v1 %}
        <tr hid="{{ row.nid }}" bid="{{ row.b_id }}">
            <td>{{ forloop.counter }}</td>
            <td>{{ row.hostname }}</td>
            <td>{{ row.ip }}</td>
            <td>{{ row.port }}</td>
            <td>{{ row.b.caption }}</td>
            <td>
                <a class="edit">编辑</a>|<a class="delete">删除</a>
            </td>
        </tr>
    {% endfor %}


    </tbody>
</table>

<h1>主机列表(字典)</h1>
<table border="1">
    <thead>
    <tr>
        <th>主机名</th>
        <th>业务线名称</th>
    </tr>
    </thead>
    <tbody>
    {% for row in v2 %}
        <tr hid="{{ row.nid }}" bid="{{ row.b_id }}">
            <td>{{ row.hostname }}</td>
            <td>{{ row.b__caption }}</td>
        </tr>
    {% endfor %}

    </tbody>
</table>
<h1>主机列表(元组)</h1>
<table border="1">
    <thead>
    <tr>
        <th>主机名</th>
        <th>业务线名称</th>
    </tr>
    </thead>
    <tbody>
    {% for row in v3 %}
        <tr hid="{{ row.0 }}" bid="{{ row.2 }}">
            <td>{{ row.1 }}</td>
            <td>{{ row.3 }}</td>
        </tr>
    {% endfor %}

    </tbody>
</table>

<div class="shade hide"></div>
<div class="add-modal hide">
    <form id="add_form" method="POST" action="/host">
        <div class="group">
            <input id="host" type="text" placeholder="主机名" name="hostname"/>
        </div>

        <div class="group">
            <input id="ip" type="text" placeholder="IP" name="ip"/>
        </div>

        <div class="group">
            <input id="port" type="text" placeholder="端口" name="port"/>
        </div>

        <div class="group">
            <select id="sel" name="b_id">
                {% for op in b_list %}
                    <option value="{{ op.id }}">{{ op.caption }}</option>
                {% endfor %}
            </select>
        </div>

        <input type="submit" value="提交"/>
        <a id="ajax_submit">悄悄提交</a>
        <input id="cancel" type="button" value="取消"/>
        <span id="erro_msg" style="color: red"></span>
    </form>
</div>

<div class="edit-modal hide">
    <form id="edit_form" method="POST" action="/host">
        <input type="text" name="nid" style="display:none"/>
        <input type="text" placeholder="主机名" name="hostname"/>
        <input type="text" placeholder="IP" name="ip"/>
        <input type="text" placeholder="端口" name="port"/>
        <select name="b_id">
            {% for op in b_list %}
                <option value="{{ op.id }}">{{ op.caption }}</option>
            {% endfor %}
        </select>
        <a id="ajax_submit_edit">确认编辑</a>
        <input id="ajax_submit_cancel" type="button" value="取消"/>
    </form>
</div>
<div class="delete-modal hide">
    <form id="delete_form" method="POST" action="/host">
        <input type="text" name="nid" style="display:none"/>
        <input type="text" placeholder="主机名" name="hostname"/>
        <input type="text" placeholder="IP" name="ip"/>
        <input type="text" placeholder="端口" name="port"/>
        <select name="b_id">
            {% for op in b_list %}
                <option value="{{ op.id }}">{{ op.caption }}</option>
            {% endfor %}
        </select>
        <a id="submit_delete">确认删除</a>
        <input id="submit_cancle" type="button" value="取消"/>
    </form>


</div>

<script src="/static/jquery-1.12.4.js"></script>
<script>django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE的解决办法(转)(代码片段

Django REST框架--认证和权限

如何在 Django 中显式重置模板片段缓存?

使用 Django 模板作为片段

python 通过django片段很多很多

JavaScript 片段在 Django 模板中不起作用