• Python-Django-Ajax进阶


    ajax上传文件:

    <h2>基于ajax上传文件</h2>
    <p>名字 <input type="text" id="filename"></p>
    <p>文件 <input type="file" id="file"></p>
    <button id="filebtn">上传文件</button>


    $('#filebtn').click(function () {
    //js取到文件
    var myfile=$('#file')[0].files[0]
    //生成一个FormData对象
    var formdata=new FormData
    //放值 //放文件
    formdata.append('name',$('#filename').val())
    formdata.append('myfile',myfile)
    $.ajax({
    url:'/fileupload/',
    type:'post',
    //这两个要必须写
    processData:false, //不预处理数据 因为FormData 已经做了
    contentType:false, //我不指定编码了 因为FormData 已经做了
    data:formdata,
    success:function (data) {
    console.log(data)
    alert(data)
    }
    })
    })


    # ajax文件上传
    def fileupload(request):
    if request.method == 'GET':
    return render(request, 'fileupload.html')
    if request.is_ajax():
    name = request.POST.get('name')
    # 文件对象
    myfile = request.FILES.get('myfile')
    import os
    path = os.path.join('media', name)
    with open(path, 'wb') as f:
    for line in myfile:
    f.write(line)
    return HttpResponse('success')

    django自带序列化:

    # ajax page,了解,django自带的序列化
    def page(request):
    if request.method == 'GET':
    users = UserInfo.objects.all()
    # json序列
    # user_dic = [{'name': user.name, 'age': user.age, 'id': user.id} for user in users]
    # return JsonResponse(user_dic, safe=False, json_dumps_params={'ensure_ascii': False})
    # 显示结果[{"name": "abc1", "age": 11, "id": 1}, {"name": "ewe", "age": 12, "id": 2}]
    # 了解,django自带的序列化
    user_dic = serializers.serialize('json', users)
    return HttpResponse(user_dic)
    # 显示结果[{"model": "app01.userinfo", "pk": 1, "fields": {"name": "abc1", "age": 11}}, {"model": "app01.userinfo", "pk": 2, "fields": {"name": "ewe", "age": 12}}]

    批量插入数据bulk_create

    # 批量插入数据bulk_create
    def pagemass(request):
    # # objes:对象列表,batch_size 一次插入数据的量
    li = []
    for i in range(200):
    # UserInfo.objects.create() #老大方式
    li.append(UserInfo(name='abc%s' % i, age=i + 1))
    ret = UserInfo.objects.bulk_create(li, 20)
    return HttpResponse('ok')

    分页器组件:

    # 分页器
    from django.core.paginator import Paginator
    def paging(request):
        users = UserInfo.objects.all().order_by('pk')
        paginator = Paginator(users, 20)
        try:
            currentpage = int(request.GET.get('page', 1))  # 默认显示第一页
            page = paginator.page(currentpage)
        except Exception as e:
            # 出错时显示第一页
            currentpage = 1
            page = paginator.page(currentpage)
        # 传入页码数,拿到的就是当前页对象
        page = paginator.page(currentpage)
        # 1 总页数是否大于11,当总页码数大于11
        if paginator.num_pages > 11:
            # 1.1 当前页码数是否小于6
            if currentpage <= 6:
                # 1.1.1 当当前页码小于6的时候,就生成11个页码数
                page_range = range(1, 12)
            # 1.2 当当前页码+5 大于等于总页码数
            elif currentpage + 5 >= paginator.num_pages:
                # 1.2.1 往后推11个页码数
                page_range = range(paginator.num_pages - 10, paginator.num_pages + 1)
            # 1.3 生成一个左5 右5的区间
            else:
                page_range = range(currentpage - 5, currentpage + 6)
        # 2 总页码数不大于11 ,有多少,显示多少
        else:
            page_range = paginator.page_range
        return render(request, 'page.html', locals())
    <table class="table">
                    <thead>
                    <tr>
                        <th>id</th>
                        <th>name</th>
                        <th>age</th>
                    </tr>
                    </thead>
                    <br>
                    <tbody>
    {#                循环的时page不是users#}
                    {% for user in page %}
                        <tr>
                            <td>{{ forloop.counter }}</td>
                            <td>{{ user.name }}</td>
                            <td>{{ user.age }}</td>
                        </tr>
                    {% endfor %}
                    </tbody>
                </table>
                <nav aria-label="Page navigation">
                    <ul class="pagination">
                        {#                    上一页判断#}
                        {% if page.has_previous %}
                            <li>
                                <a href="/paging/?page={{ page.previous_page_number }}" aria-label="Previous">
                                    <span aria-hidden="true">上一页</span>
                                </a>
                            </li>
                        {% else %}
                            <li class="disabled">
                                <a href="" aria-label="Previous">
                                    <span aria-hidden="true">上一页</span>
                                </a>
                            </li>
                        {% endif %}
    
                        {# 判断当前页面是否是循环到的页码,如果是,加active#}
                        {% for foo in page_range %}
                            {% if currentpage == foo %}
                                <li class="acitve"><a href="/paging/?page={{ foo }}">{{ foo }}</a></li>
                            {% else %}
                                <li><a href="/paging/?page={{ foo }}">{{ foo }}</a></li>
                            {% endif %}
                        {% endfor %}
    
                        {#                    下一页判断#}
                        {% if page.has_next %}
                            <li>
                                <a href="/paging/?page={{ page.next_page_number }}" aria-label="Next">
                                    <span aria-hidden="true">下一页</span>
                                </a>
                            </li>
                        {% else %}
                            <li class="disabled">
                                <a href="" aria-label="Next">
                                    <span aria-hidden="true">下一页</span>
                                </a>
                            </li>
                        {% endif %}
    
    
                    </ul>
                </nav>
    

      

    forms组件:(数据校验功能)

    <form action="">
                    <p>name <input type="text" name="name"></p>
                    <p>pwd <input type="password" name="pwd"></p>
                    <p>email <input type="email" name="email"></p>
                    <input type="submit">
                </form>
                <h1>forms的模板渲染之一(推荐)</h1>
                <form action="" method="post" novalidate>
                    <p>name: {{ myform.name }}</p>
                    <p>pwd: {{ myform.pwd }}</p>
                    <p>email: {{ myform.email }}</p>
                    <input type="submit">
                </form>
                <h1>forms的模板渲染之二(推荐!!!!!)</h1>
                <form action="" method="post" novalidate>
                    {% for item in myform %}
                        <p>{{ item.label }}:{{ item }}</p>
                    {% endfor %}
                    <input type="submit">
                </form>
                <h1>forms的模板渲染之三</h1>
                <form action="" method="post" novalidate>
                    {{ myform.as_p }}
                    <input type="submit">
                </form>
    
    from django import forms
    # 继承Form这个类
    class MyForm(forms.Form):
        # 限制name这个字段最长为8,最短为3
        name=forms.CharField(min_length=3,max_length=8,label='用户名',required=True,error_messages={'min_length':'至少为3','max_length':'最长为8,您太长了'})
        pwd=forms.CharField(min_length=3,max_length=8,label='密码',error_messages={'min_length':'至少为3','max_length':'最长为8,您太长了'})
        email=forms.EmailField(label='邮箱',error_messages={'invalid':'邮箱格式不合法','required':'这个字段必填'})
    
    # ajax register
    def register(request):
        if request.method == 'GET':
            myform=MyForm()
            return render(request, 'register.html',locals())
        else:
            # 生成对象,传参,传字典,要校验数据的字典
            # myform=MyForm(request.POST)
            # 自己写要校验的字典,数据多了,多的是不校验的,但是cleaned_data中也没有多出来的数据
            # dic={'name':'lqz','pwd':'123','email':'22@qq.com','xx':'xxx'}
            # dic={'name':'lqz','pwd':'123','email':'22'}
            # dic = {'name': 'abc', 'pwd': '122', 'email': '5555'}
            name=request.POST.get('name')
            pwd=request.POST.get('pwd')
            email=request.POST.get('email')
            dic = {'name': name, 'pwd': pwd, 'email': email}
            print(dic)
            myform = MyForm(dic)
            # 所有字典都校验通过,它就是True的
            if myform.is_valid():
                # 取出校验通过的数据
                clean_data=myform.changed_data
                print(clean_data)
                # models.UserInfo.objects.create(**clean_data)
            else:
                # 所有的错误信息
                # 只要是校验通过的值,都在cleaned_data中放着
                print(myform.changed_data)
                print(myform.errors.as_data())
                # 字典类型
                print(type(myform.errors))
                print(myform.errors.get('name'))
                from  django.forms.utils import ErrorDict
        return HttpResponse('OK')
    

      

    ajax总结:

    1 默认编码urlencode,后端按照原来form表单提交的形式取值就可以了()
    2 上传文件,form-data编码,后端按照原来form表单提交的形式取值就可以了,取数据从POST中取,取文件从FILES中取
    3 上传json格式,django不会处理数据,需要自己处理,自己从body体中取出数据处理

     TTL:

     

  • 相关阅读:
    Dockerfile基于centos镜像编译安装httpd
    Dockerfile基于centos镜像编译安装nginx
    Dockerfile介绍和常用指令
    Docker存储卷
    正则表达式
    Sed与Awk
    Shell函数
    Shell脚本基础
    Autofs
    Podman
  • 原文地址:https://www.cnblogs.com/du-jun/p/10289775.html
Copyright © 2020-2023  润新知