美文网首页
Django 练习1

Django 练习1

作者: woniuray | 来源:发表于2018-10-20 15:39 被阅读0次

    lesson 1

    1.1 创建100个Django用户

    def create_user(name):
        from django.contrib.auth.models import User
        for i in range(100):
            username = '{}_{}'.format()
            User.objects.create_user(username,username+'@qq.com','123456')
    
    create_user('ray')
    

    1.2 用视图函数获取用户列表,并分页

    1.2.1视图代码

    from django.contrib.auth.models import User
    from django.http import JsonResponse
    def user_list(request):
        if request.method == 'GET':
            # 获取所有数据
            user = User.objects.all()
            # 获取每页分的条数
            per_num = int(request.GET['per_num'])
            # 获取第几页
            page = int(request.GET['page'])
            # 转化成list
            test_list = list(user.values('id','username','email'))
            # 分页
            end_page = per_num*page
            start_page = end_page-per_num
            per_result = test_list[start_page:end_page]
            return JsonResponse(per_result,safe=False)
    

    1.22 URL代码

    dashboard.urls
    from django.conf.urls import url,include
    from .views import user_list
    urlpatterns = [
        url(r'^user_list',user_list , name='user_list')
    ]
    

    1.2.3 访问方式

    例如:访问第1页,每页4条数据

    http://127.0.0.1:8000/dashboard/user_list?page=1&per_num=4
    

    相关文章

      网友评论

          本文标题:Django 练习1

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