Django学习笔记

开始

1.创建项目:

django-admin startproject mysite 

2.创建app

cd mysite
python manage.py startapp cmdb

3.运行

python manage.py runserver 

目录结构与用途

mysite
    - mysite  项目配置
        - __init__
        - settings  配置文件
        - url       url路由配置
        - wsgi      遵循wsgi规范,上线uwsgi+nginx
        - manage.py     管理Django程序

    app:
        - migrations 数据库表结构修改记录
        - admin Django为我们的app程序自动创建的后台管理
        - apps 对当前app的配置
        - models 数据库orm,写指定的class,通过命令创建数据库结构
        - tests 单元测试
        - views app相关的所有业务,业务逻辑

配置

1.使用模板文件

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],   ##新加
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

2.静态文件配置

STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)
# TEMPLATE_DIRS = (os.path.join(BASE_DIR,  'templates'),)

3.暂时停止POST跨站请求伪造


MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    #'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

路由规则设定

  • FBV
from cmdb import views  # 在app中导入视图函数
 # Django会默认添加/,此处url路由写的什么,html的form表单中action也必须相同
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^login', views.login),  
    url(r'^home', views.home),
]
  • CBV
from mytest import views
 
urlpatterns = [
    url(r‘^index/‘, views.Index.as_view()),
]

views视图函数:

  • 形参:request client发送过来的各种信息
request.POST 
request.GET
request.methed 为POST或者GET
  • 值获取举例
 # 单个值
request.POST.get("key",None) 
request.GET.get("key",None)

 # 多个值,返回一个list
request.GET.getlist("key",None)
request.POST.getlist("key",None)

视图函数返回

  • 页面返回
  1. render 返回一个完整的html页面
  2. HttpResponse 返回字符串
  3. redirect 重定向,跳转动作不是在后台做的,不能写html模板路径
  • 返回举例
return render(request, 'login.html', {"error_msg": error_msg})  模板中通过key来获取,返回必须为一个字典,字典简直对适量不限制
return redirect("http://www.baidu.com")  # 重定向
return redirect("/home")  # 重定向
return HttpResponse("string")

模板渲染:

  • 循环
    {% for row in user_list %} 
        <tr>
            <td>{{ row.username }}</td>  获得字典key对应的值
            <td>{{ row.gender }}</td>
            <td>{{ row.email }}</td>
        </tr>
    {% endfor %}
  • 值获取:索引
eg:
    return render(request, 'login.html', {"info": "Leon","user_list":[1,2,3,4,5],"user_dict":{"k1":"v1","k2":"v2"},}) 

列表或字典获取值:
    {{ user_list.0 }}
    {{ user_list.1 }}
    {{ user_dict.k1 }}
    {{ user_dict.k2 }}
  • 条件判断
    {% if info %}
        {% if user_list.0 > 18 %}
            <a>old</a>
        {% else %}
            <a>young</a>    
        {% endif %}
        <a>用户为:info</a>
    {% else %}  
        <a>用户为空</a>
    {% endif %}

html数据提交

1. 单选框,name相同,value不同,才可以区分开,单个值用get可以获取
2. 复选框,name相同,value不同,多个用getlist获取,得到一个列表
3. select,select只有一个name,option中的value不同,多选在select中设定:multiple="multiple",后端依然使用getlist获取


4. 文件上传 :

前端:form表单中新增属性:enctype=“multipart/form-data”
后端:使用 obj = request.FILES,get(name) 来获取文件数据句柄
    import os
    file_path = os.path.join('upload',obj.name)
    f = open(file_path,mode='wb')
    for i in obj.chunks():
        f.write(i)
    f.close()

FBV和CBV

  • urls中的区别在上面
  • 视图函数写法:
from django.views import View
 
class Index(View):  # 必须继承View

    # 链接进来首先调用的是dispatch方法
    def dispatch(self, request, *args, **kwargs):  # dispatch使用了类似反射的方法,来区分get、post
        # 调用父类中的dispatch
        print(‘before‘)  # 类似装饰器的功能
        result = super(Home,self).dispatch(request, *args, **kwargs)
        print(‘after‘)  # 类似装饰器的功能
        return result

    def get(self, req):
        print(‘method is :‘ + req.method)
        return render(req, ‘index.html‘)
 
    def post(self, req):
        print(‘method is :‘ + req.method)
        return render(req, ‘index.html‘)

路由系统url

1. 基本设定

url(r'^index/', views.index),   # FBV
url(r'^home/', views.Home.as_view()), CBV

2. 正则匹配之无指定参数

url(r'^detail-(\d+).html', views.detail), 

# 举例
url(r'^detail-(\d+)-(\d+).html', views.detail),
位置参数接收:前后对应
def func(request, nid, uid):
通用参数接收:都在args里
def func(request, *args):
def func(request, *args, **kwargs):

3. 有指定参数

url(r'^detail-(?P<nid>\d+)-(?P<uid>\d+).html', views.detail)

# 举例
url(r'^detail-(?P<nid>\d+)-(?P<uid>\d+).html', views.detail)
指定参数接收:
def func(request, nid, uid):
def func(request, nid, uid):
通用参数接收:
def funct(request, **kwargs):
    kwargs = {'nid': 1, 'uid': 3}

4. name 可以根据此名称生成自己想要的URL

# urls设定

url(r'^asdfasdfasdf/', views.index, name='i1'),
url(r'^yug/(\d+)/(\d+)/', views.index, name='i2'),
url(r'^buy/(?P<pid>\d+)/(?P<nid>\d+)/', views.index, name='i3'),
        
        
# views函数设定 
def func(request, *args, **kwargs):
    from django.urls import reverse
            
    url1 = reverse('i1')                              # asdfasdfasdf/
    url2 = reverse('i2', args=(1,2,))                 # yug/1/2/
    url3 = reverse('i3', kwargs={'pid': 1, "nid": 9}) # buy/1/9/
        
# 模板中设定
xxx.html
            
    {% url "i1" %}               # asdfasdfasdf/
    {% url "i2" 1 2 %}           # yug/1/2/
    {% url "i3" pid=1 nid=9 %}   # buy/1/9/
        
# 注:
# 当前的URL
    request.path_info

5. 多级路由 app区分,多个app并行开发

  • 项目主路由设定,分发到各个app
project/urls.py
    from django.conf.urls import url,include
        urlpatterns = [
            url(r'^cmdb/', include("app01.urls")),
            url(r'^monitor/', include("app02.urls")),
        ]

app01/urls.py
    from django.conf.urls import url
    from app01 import views
        urlpatterns = [
            url(r'^login/', views.login),
        ]

6.默认值

7.命名空间

上一篇:Django笔记&教程 2-2 URL详细匹配规则


下一篇:raise ImproperlyConfigured(msg.format(name=self.urlconf_name))