zoukankan      html  css  js  c++  java
  • diango使用顺序

    使用顺序

    settings 静态文件配置

    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))  #文件夹根目录
    
    DEBUG = True   #因为启动出错调试模式 上线后改为Flase,出错不报错,给用户更好的用户体验
    
    ALLOWED_HOSTS = ['*'] #让所有的用户可以访问
    
    INSTALLED_APPS = [       #app注册
    	'app01', 
        'app01.apps.App01Config'   # 推荐写法
    ]
    
    MIDDLEWARE = [
        # 'django.middleware.csrf.CsrfViewMiddleware',   #提交POST请求注释一个中间件
    ]
    
    
    
    
    """
    如果使用sqlite3数据库
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3', 
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        }
    }
    """
    
    """
    #如果使用mysql数据库
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',   #diango的服务器引擎
            'NAME': 'bookmanager',
            'USER': 'root',
            'PASSWORD': '123',
            'HOST': '127.0.0.1',
            'PORT': 3306,
        }
    }
    
    #默认使用pymysql模块 替换
    import pymysql
    pymysql.install_as_MySQLdb()
    """
    
    
    
    
    LANGUAGE_CODE = 'en-us'       #汉语 'zh-hans'  
    
    TIME_ZONE = 'UTC'   #时区:英国的,改为亚洲上海 'Asia/Shanghai'  
    
    STATIC_URL = '/static/'    #静态文件夹的别名,配置静态文件要以/static/为开头
    
    
    STATICFILES_DIRS = [                  # 路由
        os.path.join(BASE_DIR,'static1'),   # 存放静态文件的路径
        os.path.join(BASE_DIR,'static1'),
    ]
    				 # join(BASE_DIR必须是这个,静态文件夹static1)
    					# 加上静态文件的存放路径
    
    

    models.py 映射关系

    写映射关系操作数据库

    settings 配置:

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql', #使用mysql数据库引擎
            'NAME': 'day43',		#默认操作的库
            'HOST': '127.0.0.1',	#库所在的服务器地址		
            'PORT': 3306,			#端口
            'USER': 'root',			#用户名
            'PASSWORD': '123',		#密登密码
        }
    }
    
    
    #默认使用pymysql模块 替换  也可以写在day43的__init__.py里
    import pymysql
    pymysql.install_as_MySQLdb()
    
    

    创库

    用可视化工具创建一个MySQL数据库

    创表

    class User(models.Model):
        username = models.CharField(max_length=32)  # varchar(32)
        password = models.CharField(max_length=32)  # varchar(32)
        
    #类 对象   属性
    #表 数据行 字段
    
    
    python manage.py  makemigrations  # 制作迁移文件 出现在migrations
    python manage.py migrate  # 执行SQL语句 同步 
    		#terminal里执行命令
    

    △id字段是自动添加的,如果你想要指定自定义主键,只需在其中一个字段中指定 primary_key=True 即可。如果Django发现你已经明确地设置了Field.primary_key,它将不会添加自动ID列。

    urls.py 路由

    路径 函数转换

    ==settings配置:

    STATICFILES_DIRS = [                  # 路由
        os.path.join(BASE_DIR,'static1'),   # 存放静态文件的路径
        os.path.join(BASE_DIR,'static2'),
    ]
    

    url(r^'用户输入输入的路径 0.0.0.0:80/index/',不加括号的函数名)

    urlpatterns = [ 	
        url(r'^admin/', admin.site.urls),
        url(r'^index/', index),   # 路径和函数的对应关系,
        url(r'^modal/', modal),  
    ]
    

    views.py 函数

    def index(request):  		    # 函数里写处理逻辑,request拿到网络路径,固定写法
        print(request.path_info)	# 打印网络路
    

    import 导入:

    导入返回字符串的包HttpResponse,返回html文件的包render,返回执行另一个逻辑的包

    from django.shortcuts import HttpResponse,render, redirect 
    

    导入dpp01文件中的创建数据表的类的models.py文件

    from app01 import models
    

    return 返回:

    return HttpResponse('

    index

    ')

    返回字符串

    return HttpResponse('<h1>index</h1>')         # 返回字符串
    

    return render(,,)

    返回接受到请求的网络路径要渲染的html文件和要传的值

    return render(request, 'index.html',{'k1':v1}) 
    #返回   (网络路径必添,要渲染的html文件,{别名:要传的值})
    

    return redirecct('路径')

    执行另一个逻辑

    ORM的操作

    写函数来实现增删该查

    .all 获取所有的数据

    all_publishers = models.Publisher.objects.all() 
    #变量 = 文件名.类名.对象.取值方法
    # objects.all() 查询出所有的出版社的信息,是一个对象列表
    

    .filter(pk=pk) 获取所一个数据

    第一个pk列名,第二个pk为从request中get到的

    变量 = models.User.objects.filter(password='dsb')   # 对象列表	
    # 用.first取第一个,若无,返回空列表,if 变量;判断时,不会报错,只是不会执行这个语句了
    # 用[0]取值时,,若无,取不到值,if 判断时变量,会报错
    

    get 获取所一个数据

    变量 = models.User.objects.get(password='dsb')  # 对象 特点 获取不到或者获取到多个都报错
    

    create(name=pub_name) 添加数据

    利用类的对象

    obj = models.Publisher.objects.create(name=pub_name)
    

    update(name=pub_name) 跟新数据

    templates HTML文件

    模板

    某.html的settings配置

    MIDDLEWARE = [
      
        # 'django.middleware.csrf.CsrfViewMiddleware',   #提交POST请求注释一个中间件
      
    ]
    

    hyml中的样式路径配置

    <head>  
        <title>Title</title>
        <link rel="stylesheet" href="/static/plugins/bootstrap-3.3.7-dist/css/bootstrap.min.css">
        <link rel="stylesheet" href="/static/plugins/font-awesome-4.7.0/css/font-awesome.min.css">
        
        <script src="/static/js/jquery.js"></script>
        <script src="/static/plugins/bootstrap-3.3.7-dist/js/bootstrap.js"></script>
    </head>
    

    模板语法

    △登录

    <div class="container">
    
        <form class="form-signin" method="post" action="" novalidate>
            <h2 class="form-signin-heading">Please sign in</h2>
            <label for="inputEmail" class="sr-only">用户名</label>
            <input type="text" id="inputEmail" class="form-control" name="username" placeholder="输入用户名" required=""
                   autofocus="">
            <label for="inputPassword" class="sr-only">密码</label>
            <input type="password" id="inputPassword" class="form-control" name="password" placeholder="输入密码" required="">
            <div>{{ error }}</div>
            <div class="checkbox">
                <label>
                    <input type="checkbox" value="remember-me"> Remember me
                </label>
            </div>
            <button class="btn btn-lg btn-primary btn-block">登录</button>
    
        </form>
    

    △查询所有的作者信息

        all_authors = models.Author.objects.all()
        for author in all_authors:
            print(author)
            print(author.name)
            print(author.books,type(author.books))  # 关系管理对象
            print(author.books.all(),type(author.books.all()))  # 所关联的所有的对象
    

    △for循环

    views.py传过来的参数:
    render(request,'pub.html',{'all_publishers':all_publishers}) 
    {{ all_publishers }} 
    
    html的for循环:
    {% for i in all_publishers  %}
    
    	{{ forloop.counter }}
    	{{ i }}
    	{{ i.id }}  {{ i.pk }}
    	{{ i.name }}
    	
    {% endfor %}
    
    
    

    △if

    {% if 条件 %}
    	xxx
    {% else %}	
    	xxxxx
    {% endif %}
    

    △form的注意点

    1. form标签的属性 action='提交的地址' method='post' novalidate 取消input标签自带的校验
    2. input标签必须要有name属性 有些标签有value值
    3. 需要有一个button按钮 或者 type='submit'的input

    △get 和 post

    get : 获取一个页面

    1.直接在浏览器的地址栏中输入地址 回车

    2.form表单 不指定method

    3.a标签

    参数: ?k1=v1&k2=v2

    获取参数: request.GET.get('k1')

    post : 提交数据

    form表单  method = 'post'
    

    获取数据: request.POST.get('k1')

    static1 渲染

  • 相关阅读:
    使用Docker快速搭建PHP开发环境
    docker-compose 使用介绍
    Google广告显示不正确的问题
    Hexo博客写作与图片处理的经验
    Docker-compose 建立ELK集群
    Flink101-快速示例
    Spark学习笔记01-基础
    Java Metrics工具介绍
    跨界
    苹果 icloud 把我 ipad min 所有照片丢失
  • 原文地址:https://www.cnblogs.com/-xct/p/12069396.html
Copyright © 2011-2022 走看看