Django入门(1)

发布时间:2019-10-09 10:39:25编辑:auto阅读(2044)

    Django入门

    项目创建和APP创建

    • 准备环境
    python3 
    virtualenv
    pip3
    pip3 install django==1.1
    • 项目创建,APP创建
    django-admin startproject ops
    cd ops
    python3 manage.py startapp darshboard
    cd darshboard #进入项目路径
    touch urls.py #创建路由文件
    • 项目结构如下:
    ops/
    |-- darshboard
    | |-- admin.py
    | |-- apps.py
    | |-- __init__.py
    | |-- migrations
    | |-- models.py
    | |-- tests.py
    | |-- urls.py
    | `-- views.py
    |-- db.sqlite3
    |-- manage.py
    `-- ops
        |-- __init__.py
        |-- settings.py
        |-- urls.py
        `-- wsgi.py
    • 项目注册
    # vim ops/ops/settings.py
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'darshboard.apps.DarshboardConfig' #在此处注册darshboard项目
    ]
    • 路由注册
    # vim ops/ops/urls.py
    
    from django.conf.urls import url,include
    from django.contrib import admin
    
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^darshboard/',include("darshboard.urls")), #注册app的urls
    ]
    此时,一个完整的流程就好了

    hello world

    修改darshboard的路由

    # vim ops/darshboard/urls.py
    
    from django.conf.urls import url
    from .views import index
    
    urlpatterns = [
        url(r'^hello/', index,name='index'),
    ]

    写一个视图函数

    函数视图的定义:
    a. 就是一个普通函数
    b. 接收一个HttpRequest实例作为第一个参数
    c. 然后返回一个HttpResponse的实例
    # vim ops/darshboard/views.py
    
    from django.shortcuts import render
    from django.http import HttpResponse
    
    def index(request):
        return HttpResponse('hello world')
    

    项目启动&测试

    • 启动项目
    python manage.py runserver 0:8080
    • 访问:

    打开本地浏览器输入:

    http://211.159.156.251:8080/darshboard/hello/

    即可访问!

    HttpRequest对象

    • 由Django创建

    属性如下:

    HttpRequest.scheme
    HttpRequest.body
    HttpRequest.path
    HttpRequest.method
    HttpRequest.encoding
    HttpRequest.GET
    HttpRequest.POST
    HttpRequest.META

    方法如下:

    HttpRequest.get_host()
    HttpRequest.get_port()
    HttpRequest.get_full_path()
    HttpRequest.is_secure()
    HttpRequest.is_ajax()
    • 传递一个字符串作为页面的内容到HttpResponse构造函数
    from django.http import HttpResponse
    response = HttpResponse("here is the web page")
    response = HttpResponse("Text only .please,content_type="text/plain")
    • 参考的views如下
    from django.shortcuts import render
    from django.http import HttpResponse,JsonResponse
    import json
    def index(request):
        data = {
            'name':'wanghui',
            'age':20
        }
        data_1 = ["devops","python"]
        #return HttpResponse(json.dumps(data),content_type="application/json")   #返回的content-typet
        #return HttpResponse(json.dumps(data_1),content_type="application/json")
        return JsonResponse(data_1,safe=False)
        # return HttpResponse("Hello World!!",status=599)

    模板

    为了让数据更加美观。

    POST和GET请求

    • GET请求与传参
    - method
    - GET
    • POST提交数据

    QueryDict对象

    方法练习

    #  python manage.py shell
    >>> from django.http import QueryDict
    >>> data = QueryDict('a=12&a=123&b=233')
    >>> data.urlencode()
    'a=12&a=123&b=233'

    数据库同步

    • 官方给出的数据库连接设置
    https://docs.djangoproject.com/en/1.11/ref/settings/#databases
    • 数据库同步相关命令
    python manage.py showmigrations
    python manage.py sqlmigrate sessions 0001
    python manage.py dbshell   # 进入shell模式

    创建用户

    • django-shell创建用户
    # 方式一:
    (venv3) [wanghui@www ops]$ python manage.py shell
    Python 3.6.1 (default, Jun 22 2018, 18:25:52) 
    [GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    (InteractiveConsole)
    >>> from django.contrib.auth.models import User
    >>> User.objects.create_user('rock','12272@qq.com','123456')   #创建普通用户
    >>> u = User.objects.get(username='rock')     #查找用户
    >>> u.set_password('654321')       #修改密码
    >>> u.save()                                   #保存
    -------------------------------------------------------------------------------------------------------------
    # 方式二:
    (venv3) [wanghui@www ops]$ python manage.py createsupperuser

    用户登录小练习

    重点在于对函数视图的练习

    • darshboard/views.py
    from django.shortcuts import render
    from django.http import HttpResponse,JsonResponse,QueryDict
    from django.template import loader,Context,Template
    from django.contrib.auth.models import User
    from django.contrib.auth import login,authenticate
    
    def user_login(request):
        # print(request.GET)
        # 获取提交过来的用户名&密码
        if request.method == "GET":     #get请求的话,就直接返回页面
            return render(request, 'user_login.html')
        elif request.method == "POST":  #post就要获取用户名和密码
            username = request.POST.get("username")
            password = request.POST.get("password")
        # 根据用户名取出这个记录是否存在
            user_obj = authenticate(username=username,password=password)
            if user_obj:
                login(request,user_obj)
                print("登陆成功!")
            else:
                print("登陆失败!")
        elif request.method == 'DELETE':      # 通过delete方法获取请求体
            data = QueryDict(request.body)    # 获取delete的请求体
            print(data)
        return HttpResponse("")
    • darshboard/urls.py #指定路由
    from django.conf.urls import url,include
    from django.contrib import admin
    from .views import index,index_template,index_methods,user_login
    urlpatterns = [
        url(r'^user_login',user_login)
    ]
    • darshboard/user_login.html
    <ul>
        <form method="DELETE" action="#">   
            <li>用户名:<input type="text" name="username"></li>
            <li>密码:<input type="text" name="password"></li>
            <li><input type="submit"></li>
        </form>
    </ul>

    关于delete方法的请求方式

    在linux本地机器上执行:
    curl -XDELETE http://127.0.0.1:8080/darshboard/user_login/ -d username=rock -d password=654321

关键字