美文网首页
django 补充

django 补充

作者: 两分与桥 | 来源:发表于2018-05-20 23:29 被阅读7次

django 上传文件,

# views.py 文件
from django.shortcuts import render
from django.shortcuts import HttpResponse
# Create your views here.

def upload(request):
    if request.method == "GET":
        return render(request,"upload.html")
    else:
        user = request.POST.get("user")

        print("user:",user)
        img = request.FILES.get("img")
        print(type(img))
        print(img.name)
        print(img.size)
        f = open(img.name,"wb")
        for line in img.chunks():
            f.write(line)
        f.close()
        return HttpResponse("get")

# upload.html 文件
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/upload.html/" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <input type="text" name="user">
    <input type="file" name="img">
    <input type="submit" value="提交">
</form>
</body>
</html>


上传文件也可以过检测,不过要记得添加 request.FILES 到定制的form类中,

from django.shortcuts import render
from django.shortcuts import HttpResponse
from django import forms
from django.forms import fields

class UploadForm(forms.Form):
    user = fields.CharField()
    img = fields.FileField()

def upload(request):
    if request.method == "GET":
        return render(request,"upload.html")
    else:
        obj = UploadForm(request.POST,request.FILES) # 这里要添加 request.FILES
        if obj.is_valid():
            user = obj.cleaned_data["user"]
            img = obj.cleaned_data["img"]
            # print("user:",user) 
            # print(img.name) img 为对象
            # print(img.size)
            f = open(img.name,"wb")
            for line in img.chunks():
                f.write(line)
            f.close()
        else:
            print(obj.errors)
        return HttpResponse("get")



上图中的选择文件的提示框也可以修改为别的按钮框,但是django不支持这个,但是我们可以用覆盖的方法来做出这个效果,也就是让默认的按钮框透明度为1,(透明),覆盖到我们设定的按钮上就行了。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/static/bootstrap.css">
    <style>
        .inputfile{
            position: absolute;
            color: red;
            margin-left:5px;
            margin-top: -30px;
            opacity: 0;
        }
    </style>
</head>
<body>
    <div style="position: relative">
        <form action="/upload.html/" method="post" enctype="multipart/form-data">
            {% csrf_token %}
            <p><input type="text" name="user"></p>
            <p class="btn btn-primary">上传文件</p>
            <input type="file" name="img" class="inputfile">
            <p></p>
            <p><input type="submit" value="提交"></p>
        </form>
    </div>
</body>
</html>


note

1.ajax参数
        
        url:
        type:
        data:
            1. value不能是字典 {k1:'v1',k2:[1,2,3,],k3: JSON.stringify({})}
            2. $('').serilizer()
        dataType:"JSON",# text,html,xml
        单词太长了 traditional:
        success:function(arg){
            # arg=>obj
        },
        error:function(){
            
        }
    2. 序列化
        JavaScript:
            JSON.parse()
            JSON.stringify()
        
        Django:
            json.dumps()
            json.loads()
            问题:
                serilize:  model.TB.objects.all()
                
                json:  list(model.TB.objects.values())
                json:  list(model.TB.objects.values_list())
            
    
    3. Form
        作用:用于验证+(生成HTML+保存上次提交的数据)
        使用:
            1.创建类
            2.创建字段()
            3. 验证用户输入:
                obj = Form(request.POST,request.FILES)
                if obj.is_valid():
                    obj.cleaned_data
                else:
                    obj.errors
            4. clean_字段
            
            5. clean()  _post_clean()
            
            PS: __all__
                
            
    4. 分页组件
    
        a. 内置
        b. 扩展
        c. 自定义
        
    5. XSS攻击
        跨站脚本攻击:
            
        防止:
            - 其他人输入的内容     不用safe
            - 自己输入的内容       可用safe
        
        
        <script>
            for(var i=0;i<9999;i++){
                alert(i)
            }
        </script>
        
        
        <script>
            获取本地cookie,发送到另外一个网站
        </script>

一道python的列表题

def func(arg,li=[]):
    li.append(arg)
    return li

v1 = func(1) # python 的 函数指向
print(v1)
v2 = func(2,[])
print(v2)
v3 = func(3)
print(v3)

# 要仔细想一想,
输出结果是:
[1]
[2]
[1, 3]

把输出结果的位置换成下面的,结果也不相同

def func(arg,li=[]):
    li.append(arg)
    return li

v1 = func(1)
v2 = func(2,[])
v3 = func(3)
print(v1)
print(v2)
print(v3)

输出结果:
[1, 3]
[2]
[1, 3]

还有一道,要十分注意python的内存地址

n1 = ['11','22','33','44','55']
n2 = n1
n3 = n1[:] # 切片就是复制一份到 n3

n2[0] = '666'
n3[1] = '999'

print(n1) # ['666','22','33','44','55']
print(n2) # ['666','22','33','44','55']
print(n3) # ['11','999','33','44','55']

在表查询中,多次进入数据库查询数据也是很影响效率的,可以用select_related 一次获取关联数据

class Teacher(models.Model):
    name = models.CharField(max_length=32)
    age = models.IntegerField()

class Student(models.Model):
    name = models.CharField(max_length=32)
    th = models.ForeignKey("Teacher",on_delete=models.CASCADE)

        # student_list = models.Student.objects.all() # 一次
        # for row in student_list:
        #     print(row.id, row.name, row.th_id) # 三次
        #     print(row.th.name)

        # 性能相关:表之间进行join连表操作,一次性获取关联的数据
        student_list = models.Student.objects.all().select_related("th") 
        for row in student_list:
            print(row.id, row.name, row.th_id)
            print(row.th.name)
    
    - Django Model操作补充
        参考博客:http://www.cnblogs.com/wupeiqi/articles/6216618.html
        1. 创建类
            class UserInfo(model.Model):
                
                age = CharFiled(是否为空,类型,长度,列名,索引=True||||错误提示,自定义验证规则)
                ..
                ..
                
                ### 一对多 
                ### 一对一 也就是一对多的基础上加上unique
                    - on_delete**
                
                
                ### 多对多 m = models.ManyToManyField(to="User")
             # 使用ManytoManyField只能在第三张表中创建三列数据
             # 要创建超过三条数据,就要自己创建第三张表

    class UserToTag(models.Model):
            u = models.ForeignKey(to="User")
            t = models.ForeignKey(to="Tag")
            class Meta:
            unique_together=[ # 联合唯一    
                ('u','t'),
        ]

                    - 第三张表:a.自动创建;b.手动创建; c. 手动+自动
                
                    ### 自关联:互粉 ###
                    
            a. 索引
        model 的索引就是建立一张查询表,以二叉树的方式存储,使得可以快速查询
        但是算是建立了索引,查询时也不一定走的的索引查询,具体可以看
        博客:http://www.cnblogs.com/wupeiqi/articles/5716963.html
            b. 一对多: on_delete
            c. 一对一和一对多是什么关系? unique=true
            d. 多对多:
                - a.自动创建;b.手动创建; c. 手动+自动
                - ### 自关联:互粉 ###
                
            PS:related_name 联表查询,可以加快速度

            
        2. 操作类
            obj = UserInfo.objects.all().all().all()

创建数据库
    .related_name
    .related_query_name
    # 表和表之间可以自关联
        多对多自关联 --> 互粉     related_name
        一对多自关联 --> 评论楼   related_name


操作数据库
    .all
    .values
    .values_list
    .delete
    .filter
    .update
    .create
    .m.add
    .m.set
    .m.clear
    .m.remove
    .only
    .defer
    .extra
    .raw
    原生SQL
        select_related
        prefetch_related




Django提供的现成功能:
    models.tb.objects......
    
    性能相关:
        models.UserInfo.objects.all()
    
        a. select_related('跨表字段') : 一次连表查询获取所有的数据
            models.UserInfo.objects.select_related('ut')
            # 连表查询性能低 UserInfo,UserType
            
        b. prefetch_related
            models.UserInfo.objects.prefetch_related('ut')
            # select * from userinfo where id < 20
            # 计算获取到的所有用户的用户类型ID [1,]
            # select * from usertype where id in [1,]
    
    
自己写SQL语句:   
    # from django.db import connection, connections
    # cursor = connection.cursor()  # cursor = connections['default'].cursor()
    # cursor.execute("""SELECT * from auth_user where id = %s""", [1])
    # row = cursor.fetchone()
    
    models.UserInfo.objects.raw('select id,name from userinfo')
    
    
    Entry.objects.extra(select={'new_id': "select col from sometable where othercol > %s"}, select_params=(1,))

面试题

    <script>
        var v = 123;
        function foo(){
            var v = 456;
            function inner(){
                console.log(v)
            }
            return inner
        }
        result = foo();
        result();
    </script>
这个打印结果是 456,代码在执行之前作用域已经创建,一个函数就是一个作用域,通过作用域去寻找值。
    <script>
        Name='root';
        Age = 18;
        function Foo(name,age){
            this.Name = name;
            this.Age = age;
            this.Func = function(){
                // this = obj
                console.log(this.Name,this.Age);
                (function(){  // this = window,
                     console.log(this.Name,this.Age);
                })();
            }
        }
        obj = new Foo('alex',666);
        obj.Func()
    </script>
输出结果:
alex 666
root 18

1. js面向对象,没有类的概念,用函数来充当类,

function Func(name,age){ 
    this.Name = name;  # this 指代对象,也就是下面的 obj
    this.Age = age;   
}
obj = new Func('root',18) 用这样来调用类

2. this关键字
# 每个函数中都有this
# 函数调用时,this=window
# 类new时,this=obj

function func(){
    # 当做函数执行函数时,也就是 func() 执行时,this=window
    console.log(this);
}
func()


function Func(){
    # 当做函数执行函数时,obj = new Func(), this=obj
    console.log(this);
}
obj = new Func()


3. js中无字典,只有对象

Name = 'alex'
obj = {
    Name: 'root',
    Age: 18,
    Func: function(){
        # this=obj
        console.log(this.Name) # root 
        
        function inner(){
            # this=window
            console.log(this.Name)
        }
        inner()
    }
}
相当于new了对象 obj

obj.Func()



Name = 'alex'
obj = {
    Name: 'root',
    Age: 18,
    Func: function(){
        # this=obj
        console.log(this.Name) # root 
        var that =this;
        function inner(){
            # this=window
            console.log(that.Name)
        }
        inner()
        // 自执行函数
        (function(){
            console.log(that.Name)
        })() # 创建并执行
    }
}
相当于new了对象 obj

obj.Func()

数据的联合唯一,

# class UserToTag(models.Model):
#     u = models.ForeignKey(to="User")
#     t = models.ForeignKey(to="Tag")
#     class Meta:
#         unique_together=[ # 联合唯一
#             ('u','t'),
#         ]

相关文章

  • django 补充

    django 上传文件, 上传文件也可以过检测,不过要记得添加 request.FILES 到定制的form类中,...

  • django_rfw_3

    本篇内容 补充: 关于实例化 回顾 为什么用 django restframework? 关于认证、权限、节流,只...

  • http 请求升级为https

    环境 django + nginx + uwsgi + https先申请阿里云SSL证书 然后补充信息等待申请成功...

  • Django_补充小技巧

    1.Templates过滤器 什么是过滤器? 写在模板中,属于Django模板语言 可以修改模板中的变量,...

  • Django:rest framework补充ContentTy

    ContentType django内置的ContentType组件就是帮我们做连表操作如果一个表与其他表有多个外...

  • Django Rest Framework 项目初始化

    项目使用Django Rest Framework时,避免不了安装,配置,遂逐渐补充在这,偶尔用到,便于查找。 添...

  • Python Django Web

    一、环境搭建: 知识补充: Python下有许多款不同的 Web 框架。Django是重量级选手中最有代表性的一位...

  • django 本地开发中的坑,不定期更新

    不定期更新,补充django开发中遇到的坑 在urls.py中新加了路由之后,记得ctrl+c结束运行的本地ser...

  • Django 引入pjax

    django-pjax 博大精深,可以提升文件目录浏览速度,支持浏览器缓存,先来一版最简单的,等待后面继续补充1、...

  • 使用宝塔面板快速部署Django项目

    本篇内容主要参考:使用宝塔快速部署Django项目文章,这篇文章在过程有些遗漏和补全的地方,在这里进行补充来做记录...

网友评论

      本文标题:django 补充

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