引述
Python的WEB框架有Django、Tornado、Flask 等多种,Django相较与其他WEB框架其优势为:大而全,框架本身集成了ORM、模型绑定、模板引擎、缓存、Session等诸多功能。
基本配置
一、创建django程序
-
终端命令:django-admin startproject sitename
-
IDE创建Django程序时,本质上都是自动执行上述命令
其他常用命令:
python manage.py runserver127.0.0.1:8000
python manage.py startapp appname
python manage.py syncdb
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
二、程序目录
三、配置文件
1.数据库
1 DATABASES = { 2 'default': { 3 'ENGINE': 'django.db.backends.mysql', 4 'NAME':'dbname', 5 'USER': 'root', 6 'PASSWORD': 'xxx', 7 'HOST': '', 8 'PORT': , 9 } 10 }
1 # 由于Django内部连接MySQL时使用的是MySQLdb模块,而python3中还无此模块,所以需要使用pymysql来代替 2 3 # 如下设置放置的与project同名的配置的 __init__.py文件中 4 5 import pymysql 6 pymysql.install_as_MySQLdb()
2.模板
1 TEMPLATE_DIRS = ( 2 os.path.join(BASE_DIR,'templates'), 3 )
3.静态文件
https://www.cnblogs.com/open-yang/p/11221829.html
1 STATICFILES_DIRS = ( 2 os.path.join(BASE_DIR,'static'), 3 )
路由系统
基本操作:普通url+带正则url(传参数)+路由分发+反生成url
1 """directory_structure URL Configuration 2 3 The `urlpatterns` list routes URLs to views. For more information please see: 4 https://docs.djangoproject.com/en/2.1/topics/http/urls/ 5 Examples: 6 Function views 7 1. Add an import: from my_app import views 8 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 Class-based views 10 1. Add an import: from other_app.views import Home 11 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 Including another URLconf 13 1. Import the include() function: from django.urls import include, path 14 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 """ 16 from django.contrib import admin 17 from django.urls import path, re_path, include 18 from app01 import views 19 20 21 urlpatterns = [ 22 path('admin/', admin.site.urls), 23 path('app01/', include('app01.urls')), 24 # path('login/', views.login, name='m1'), # 在前端页面使用反生成url 25 26 # re_path('edit1/(w+)', views.edit1, name='m2'), 27 # 动态url 在前端页面使用反生成url 有几个参数就在前端页面后边添加参数就是了 {% url 'm2' i %} 28 29 # re_path('index/(?P<a1>d+)/', views.index, name='n1'), 根据别名反生成url在后台的使用 30 31 # path('', views.index), 32 # path('app01/', include('app01.urls')), 33 # path('app02/', include('app02.urls')), 34 35 ]
1 from django.urls import path, re_path 2 from app01 import views 3 4 urlpatterns = [ 5 # re_path('index$', views.index), 6 7 # path('index/', views.index), # 静态url 一一对应 8 # re_path('edit/(w+)', views.edit), # 动态url 可以变传参 9 # re_path('edit/(d+).html$', views.edit), # 伪静态 对权重好点 10 # re_path('edit/(?P<a1>w+)/(?P<a2>w+)/', views.edit), 11 # re_path('edit/(w+)/(?P<a2>w+)/', views.edit), # 报错 12 13 # 对数据库简单操作 14 path('newindex/', views.newindex) 15 ]
1 from django.shortcuts import render, HttpResponse, reverse 2 3 # def index(request, a1): 4 # user_list = [ 5 # 'aaa', 'bbb', 'ccc' 6 # ] 7 # # v = reverse('n1') 8 # # v = reverse('n1', args=(1,)) 9 # v = reverse('n1', kwargs={"a1": 1111}) 10 # print(v) 11 # return render(request, 'index.html', {'user_list': user_list}) 12 # 13 # 14 # def edit(request, a1, a2): 15 # """ 16 # def edit(request, *args, **kwargs): 17 # 注意这里改成可边长参数 *args **kwargs要报错 url中要统一都要把参数带上 18 # :param request: 19 # :param a1: 20 # :param a2: 21 # :return: 22 # """ 23 # print(a1, a2) 24 # return HttpResponse('.....') 25 # 26 # 27 # def edit1(request, a1): 28 # return HttpResponse('.....') 29 # 30 # 31 # def login(request): 32 # return render(request, 'login.html') 33 34 35 # ################# 对数据库操作 ######################### 36 37 from app01 import models 38 39 40 def newindex(request): 41 """ 42 单表操作UserGroup 43 :param request: 44 :return: 45 """ 46 # 新增 47 # models.UserGroup.objects.create(title="销售部") 48 # models.UserInfo.objects.create(username='孙大圣', password='pwd', age=18, ug_id=1) 49 50 # 查找 51 # group_list = models.UserGroup.objects.all() # group_list是QuerySet类型 相当于一个列表 52 # for row in group_list: 53 # print(row.id, row.title) 54 55 # group_list = models.UserGroup.objects.filter(id=1) 56 # group_list = models.UserGroup.objects.filter(id__gt=1)#大于 57 # group_list = models.UserGroup.objects.filter(id__lt=1) #小于 58 59 # 删除 60 # models.UserGroup.objects.filter(id=2).delete() 61 62 # 更新 63 # models.UserGroup.objects.filter(id=2).update(title='公关部') 64 # return render(request, 'newindex.html', {'group_list': group_list}) 65 return HttpResponse('......')
1 from django.db import models 2 3 4 class UserGroup(models.Model): 5 title = models.CharField(max_length=32) 6 7 8 class UserInfo(models.Model): 9 username = models.CharField(max_length=32) 10 password = models.CharField(max_length=64) 11 # age = models.IntegerField(null=True) 12 age = models.IntegerField(default=1) # 处理这种问题直接可以设置成空或者默认给个值 因为此时在数据库有数据 13 ug = models.ForeignKey("UserGroup", on_delete=models.CASCADE, null=True)
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 </head> 7 <body> 8 <ul> 9 {% for i in user_list %} 10 {# <li>{{ i }}| <a href="/edit/?nid={{ i }}">编辑</a></li> SEO权重比较低/get传参经常变动#} 11 {# <li>{{ i }}| <a href="/edit/{{ i }}/">编辑</a></li>#} 12 <li>{{ i }}| <a href="{% url 'm2' i %}">编辑</a></li> 13 {% endfor %} 14 </ul> 15 </body> 16 </html>
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 </head> 7 <body> 8 <form action="{% url 'm1' %}" method="post"> 9 <input type="text"> 10 </form> 11 </body> 12 </html>
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 </head> 7 <body> 8 <ul> 9 {% for row in group_list %} 10 <li>{{ row.id }} == {{ row.title }}</li> 11 {% endfor %} 12 13 </ul> 14 </body> 15 </html>
1 from django.urls import path, re_path 2 from app02 import views 3 4 urlpatterns = [ 5 path('index/', views.index), 6 7 8 # path('index/', views.index), # 静态url 一一对应 9 # re_path('edit/(w+)', views.edit), # 动态url 可以变传参 10 # re_path('edit/(d+).html$', views.edit), # 伪静态 对权重好点 11 # re_path('edit/(?P<a1>w+)/(?P<a2>w+)/', views.edit), 12 # re_path('edit/(w+)/(?P<a2>w+)/', views.edit), # 报错 13 ]
1 from django.shortcuts import render, HttpResponse 2 3 4 def index(request): 5 return HttpResponse('.......')
模板基本操作
1 """mysite URL Configuration 2 3 The `urlpatterns` list routes URLs to views. For more information please see: 4 https://docs.djangoproject.com/en/2.1/topics/http/urls/ 5 Examples: 6 Function views 7 1. Add an import: from my_app import views 8 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 Class-based views 10 1. Add an import: from other_app.views import Home 11 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 Including another URLconf 13 1. Import the include() function: from django.urls import include, path 14 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 """ 16 from django.contrib import admin 17 from django.urls import path 18 from django.shortcuts import HttpResponse, render, redirect 19 20 21 def login(request): 22 """ 23 处理请求逻辑 24 :param request:用户请求相关所有信息并返回内容 25 :return: 26 """ 27 # 自动找到模板下的login.html看配置文件template 28 # return HttpResponse('login') 29 if request.method == 'GET': 30 return render(request, 'login.html') 31 else: 32 u = request.POST.get('username') 33 p = request.POST.get('password') 34 if u == 'root' and p == '123': 35 return redirect('/index/') 36 else: 37 return render(request, 'login.html', context={'msg': '用户名登录失败'}) 38 39 40 def index(request): 41 return render(request, 42 'index.html', 43 { 44 'msg': 123, 45 'user_list': ['励志', '理发'], 46 'user_dict': {'k1': 'v1', 'k2': 'v2'}, 47 'user_list_dict': [ 48 {'id': 1, 'name': 'eric1', 'email': 'eric13690@163.com'}, 49 {'id': 2, 'name': 'eric2', 'email': 'eric23690@163.com'}, 50 {'id': 3, 'name': 'eric3', 'email': 'eric33690@163.com'}, 51 ] 52 } 53 ) 54 55 56 urlpatterns = [ 57 path('admin/', admin.site.urls), 58 path('login/', login), 59 path('index/', index), 60 ] 61 # 路由系统
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 <link rel="stylesheet" href="/static/commons.css"> 7 </head> 8 <body> 9 <h1>用户登录</h1> 10 <form action="/login/" method="post"> 11 {% csrf_token %} 12 <input type="text" name="username"> 13 <input type="password" name="password"> 14 <input type="submit" value="登录"> 15 {{ msg }} 16 </form> 17 18 </body> 19 </html>
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 </head> 7 <body> 8 <h3>模板简单使用</h3> 9 {{ msg }} 10 <p>{{ user_list.0 }}</p> 11 <p>{{ user_list.1 }}</p> 12 <p>{{ user_dict.k1 }}</p> 13 <p>{{ user_dict.k2 }}</p> 14 {% for user in user_list %} 15 <h4>{{ user }}</h4> 16 {% endfor %} 17 {% for user in user_list %} 18 <li>{{ user }}</li> 19 {% endfor %} 20 <ul> 21 {% for user in user_list %} 22 <li>{{ user }}</li> 23 {% endfor %} 24 </ul> 25 <table border="1"> 26 {% for row in user_list_dict %} 27 <tr> 28 <td>{{ row.id }}</td> 29 <td>{{ row.name }}</td> 30 <td>{{ row.email }}</td> 31 <td><a href="">编辑</a>|<a href="/del/?nid={{ row.id }}">删除</a></td> 32 </tr> 33 {% endfor %} 34 </table> 35 36 </body> 37 </html>
总结:
1、单一路由对应
1 url(r'^index$', views.index),
2、基于正则的路由
1 url(r'^index/(d*)', views.index), 2 url(r'^manage/(?P<name>w*)/(?P<id>d*)', views.manage),
3、添加额外的参数
1 url(r'^manage/(?P<name>w*)', views.manage,{'id':333}),
4、为路由映射设置名称
1 url(r'^home', views.home, name='h1'), 2 url(r'^index/(d*)', views.index, name='h2'),
设置名称之后,可以在不同的地方调用,如:
- 模板中使用生成URL {% url 'h2' 2012 %}
- 函数中使用生成URL reverse('h2', args=(2012,)) 路径:django.urls.reverse
- Model中使用获取URL 自定义get_absolute_url() 方法
1 class NewType(models.Model): 2 caption = models.CharField(max_length=16) 3 4 5 def get_absolute_url(self): 6 """ 7 为每个对象生成一个URL 8 应用:在对象列表中生成查看详细的URL,使用此方法即可!!! 9 :return: 10 """ 11 # return '/%s/%s' % (self._meta.db_table, self.id) 12 # 或 13 from django.urls import reverse 14 return reverse('NewType.Detail', kwargs={'nid': self.id})
获取请求匹配成功的URL信息:request.resolver_match
5、根据app对路由规则进行分类
1 url(r'^web/',include('web.urls')),
6、命名空间
a. project.urls.py
1 from django.conf.urls import url,include 2 3 urlpatterns = [ 4 url(r'^a/', include('app01.urls', namespace='author-polls')), 5 url(r'^b/', include('app01.urls', namespace='publisher-polls')), 6 ]
b. app01.urls.py
1 from django.conf.urls import url 2 from app01 import views 3 4 app_name = 'app01' 5 urlpatterns = [ 6 url(r'^(?P<pk>d+)/$', views.detail, name='detail') 7 ]
c. app01.views.py
1 def detail(request, pk): 2 print(request.resolver_match) 3 return HttpResponse(pk)
以上定义带命名空间的url之后,使用name生成URL时候,应该如下:
- v = reverse('app01:detail', kwargs={'pk':11})
- {% url 'app01:detail' pk=12 pp=99 %}
django中的路由系统和其他语言的框架有所不同,在django中每一个请求的url都要有一条路由映射,这样才能将请求交给对一个的view中的函数去处理。其他大部分的Web框架则是对一类的url请求做一条路由映射,从而是路由系统变得简洁。
模板小结:
1.模版语言
模板中也有自己的语言,该语言可以实现数据展示
{{ item }}
{% for item in item_list %} <a>{{ item }}</a> {% endfor %}
forloop.counter
forloop.first
forloop.last
{% if ordered_warranty %} {% else %} {% endif %}
母板:{% block title %}{% endblock %}
子板:{% extends "base.html" %}
{% block title %}{% endblock %}
母板是拿来给子板继承的,子板只能用一次
帮助方法:
{{ item.event_start|date:"Y-m-d H:i:s"}}
{{ bio|truncatewords:"30" }}
{{ my_list|first|upper }}
{{ name|lower }}
2、自定义simple_tag
a、在app中创建templatetags模块
b、创建任意 .py 文件,如:xx.py
1 #!/usr/bin/env python 2 #coding:utf-8 3 4 from django import template 5 from django.utils.safestring import mark_safe 6 7 register = template.Library() 8 9 @register.simple_tag 10 def my_simple_time(v1,v2,v3): 11 return v1 + v2 + v3 12 13 @register.simple_tag 14 def my_input(id,arg): 15 result = "<input type='text' id='%s' class='%s' />" %(id,arg,) 16 return mark_safe(result)
c、在使用自定义simple_tag的html文件中导入之前创建的 xx.py 文件名
1 {% load xx %}
d、使用simple_tag
1 {% my_simple_time 1 2 3%} 2 {% my_input 'id_username' 'hide'%}
e、在settings中配置当前app,不然django无法找到自定义的simple_tag
1 INSTALLED_APPS = ( 2 'django.contrib.admin', 3 'django.contrib.auth', 4 'django.contrib.contenttypes', 5 'django.contrib.sessions', 6 'django.contrib.messages', 7 'django.contrib.staticfiles', 8 'app01', 9 )
3.自定义filter
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 4 from django import template 5 6 register = template.Library() 7 8 9 @register.filter 10 def my_upper(value, arg): 11 return value + arg
<h4>特别漂亮的组件 补充include模板导入</h4> <div> <input class="title" type="text"> <input class="content" type="text"> </div>
1 def test(request): 2 3 return render(request, 'test.html', {'msg': 'mchotdog'})
{% load xx %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> {% include 'pub.html' %} {{ msg | my_upper:'泽帅'}} <p><a>不能多传参数最多两个参数但是支持模板中循环判断语句,但是simple_tag能多传参数但是不支持模板判断循环判断语句</a></p> {% include 'pub.html' %} </body> </html>
更多见文档:https://docs.djangoproject.com/en/1.10/ref/templates/language/