Django知识点
Posted dev0ps
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django知识点相关的知识,希望对你有一定的参考价值。
一、Django
pip3 install django
C:Python35Scripts
# 创建Django工程
django-admin startproject 【工程名称】
mysite
- mysite # 对整个程序进行配置
- init
- settings # 配置文件
- url # URL对应关系
- wsgi # 遵循WSIG规范,uwsgi + nginx
- manage.py # 管理Django程序:
- python manage.py
- python manage.py startapp xx
- python manage.py makemigrations
- python manage.py migrate
# 运行Django功能
python manage.py runserver 127.0.0.1:8001
chouti
- chouti
- 配置
- 主站 app
- 后台管理 app
# 创建app
python manage.py startapp cmdb
python manage.py startapp openstack
python manage.py startapp xxoo....
app:
migrations 数据修改表结构
admin Django为我们提供的后台管理
apps 配置当前app
models ORM,写指定的类 通过命令可以创建数据库结构
tests 单元测试
views 业务代码
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
STATICFILES_DIRS = (
os.path.join(BASE_DIR, ‘static‘),
)
<link rel="stylesheet" href="/static/commons.css" />
内容整理
1. 创建Django工程
django-admin startproject 工程名
2. 创建APP
cd 工程名
python manage.py startapp cmdb
3、静态文件
project.settings.py
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
4、模板路径
DIRS ==> [os.path.join(BASE_DIR,‘templates‘),]
5、settings中
middlerware
# 注释 csrf
6、定义路由规则
url.py
"login" --> 函数名
7、定义视图函数
app下views.py
def func(request):
# request.method GET / POST
# http://127.0.0.1:8009/home?nid=123&name=alex
# request.GET.get(‘‘,None) # 获取请求发来的而数据
# request.POST.get(‘‘,None)
# return HttpResponse("字符串")
# return render(request, "html模板的路径")
# return redirect(‘/只能填URL‘)
8、模板渲染
特殊的模板语言
-- {{ 变量名 }}
def func(request):
return render(request, "index.html", {‘current_user‘: "alex"})
index.html
<html>
..
<body>
<div>{{current_user}}</div>
</body>
</html>
====> 最后生成的字符串
<html>
..
<body>
<div>alex</div>
</body>
</html>
-- For循环
def func(request):
return render(request, "index.html", {‘current_user‘: "alex", ‘user_list‘: [‘alex‘,‘eric‘]})
index.html
<html>
..
<body>
<div>{{current_user}}</div>
<ul>
{% for row in user_list %}
{% if row == "alex" %}
<li>{{ row }}</li>
{% endif %}
{% endfor %}
</ul>
</body>
</html>
#####索引#################
def func(request):
return render(request, "index.html", {
‘current_user‘: "alex",
‘user_list‘: [‘alex‘,‘eric‘],
‘user_dict‘: {‘k1‘: ‘v1‘, ‘k2‘: ‘v2‘}})
index.html
<html>
..
<body>
<div>{{current_user}}</div>
<a> {{ user_list.1 }} </a>
<a> {{ user_dict.k1 }} </a>
<a> {{ user_dict.k2 }} </a>
</body>
</html>
###### 条件
def func(request):
return render(request, "index.html", {
‘current_user‘: "alex",
"age": 18,
‘user_list‘: [‘alex‘,‘eric‘],
‘user_dict‘: {‘k1‘: ‘v1‘, ‘k2‘: ‘v2‘}})
index.html
<html>
..
<body>
<div>{{current_user}}</div>
<a> {{ user_list.1 }} </a>
<a> {{ user_dict.k1 }} </a>
<a> {{ user_dict.k2 }} </a>
{% if age %}
<a>有年龄</a>
{% if age > 16 %}
<a>老男人</a>
{% else %}
<a>小鲜肉</a>
{% endif %}
{% else %}
<a>无年龄</a>
{% endif %}
</body>
</html>
二、路由系统,URL
1、url(r‘^index/‘, views.index),
url(r‘^home/‘, views.Home.as_view()),
2、url(r‘^detail-(d+).html‘, views.detail),
3、url(r‘^detail-(?P<nid>d+)-(?P<uid>d+).html‘, views.detail)
PS:
def detail(request, *args,**kwargs):
pass
实战:
a.
url(r‘^detail-(d+)-(d+).html‘, views.detail),
def func(request, nid, uid):
pass
def func(request, *args):
args = (2,9)
def func(request, *args, **kwargs):
args = (2,9)
b.
url(r‘^detail-(?P<nid>d+)-(?P<uid>d+).html‘, views.detail)
def func(request, nid, uid):
pass
def funct(request, **kwargs):
kwargs = {‘nid‘: 1, ‘uid‘: 3}
def func(request, *args, **kwargs):
args = (2,9)
4、 name
对URL路由关系进行命名, ***** 以后可以根据此名称生成自己想要的URL *****
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‘),
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、多级路由
project/urls.py
from django.conf.urls import url,include
from django.contrib import admin
urlpatterns = [
url(r‘^cmdb/‘, include("app01.urls")),
url(r‘^monitor/‘, include("app02.urls")),
]
app01/urls.py
from django.conf.urls import url,include
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r‘^login/‘, views.login),
]
app02/urls.py
from django.conf.urls import url,include
from django.contrib import admin
from app02 import views
urlpatterns = [
url(r‘^login/‘, views.login),
]
6、默认值(欠)
7、命名空间(欠)
二、视图
1、获取用户请求数据
request.GET
request.POST
request.FILES
PS:
GET:获取数据
POST:提交数据
2、checkbox等多选的内容
request.POST.getlist()
3、上传文件
# 上传文件,form标签做特殊设置
obj = request.FILES.get(‘fafafa‘)
obj.name
f = open(obj.name, mode=‘wb‘)
for item in obj.chunks():
f.write(item)
f.close()
4、FBV & CBV
function base view
url.py
index -> 函数名
view.py
def 函数(request):
...
====》
/index/ -> 函数名
/index/ -> 类
====》
建议:两者都用
5、装饰器
欠
三、模板
四、ORM操作
select * from tb where id > 1
# 对应关系
models.tb.objects.filter(id__gt=1)
models.tb.objects.filter(id=1)
models.tb.objects.filter(id__lt=1)
创建类
a. 先写类
from django.db import models
# app01_userinfo
class UserInfo(models.Model):
# id列,自增,主键
# 用户名列,字符串类型,指定长度
username = models.CharField(max_length=32)
password = models.CharField(max_length=64)
b. 注册APP
INSTALLED_APPS = [
‘django.contrib.admin‘,
‘django.contrib.auth‘,
‘django.contrib.contenttypes‘,
‘django.contrib.sessions‘,
‘django.contrib.messages‘,
‘django.contrib.staticfiles‘,
‘app01‘,
]
c. 执行命令
python manage.py makemigrations
python manage.py migrate
d. ********** 注意 ***********
Django默认使用mysqldb模块链接MySQL
主动修改为pymysql,在project同名文件夹下的__init__文件中添加如下代码即可:
import pymysql
pymysql.install_as_MySQLdb()
1. 根据类自动创建数据库表
# app下的models.py
python manage.py makemigrations
python manage.py migrate
字段:
字符串类型
数字
时间
二进制
自增(primary_key=True)
字段的参数:
null -> db是否可以为空
default -> 默认值
primary_key -> 主键
db_column -> 列名
db_index -> 索引
unique -> 唯一索引
unique_for_date ->
unique_for_month
unique_for_year
auto_now -> 创建时,自动生成时间
auto_now_add -> 更新时,自动更新为当前时间
# obj = UserGroup.objects.filter(id=1).update(caption=‘CEO‘)
# obj = UserGroup.objects.filter(id=1).first()
# obj.caption = "CEO"
# obj.save()
choices -> django admin中显示下拉框,避免连表查询
blank -> django admin是否可以为空
verbose_name -> django admin显示字段中文
editable -> django admin是否可以被编辑
error_messages -> 错误信息欠
help_text -> django admin提示
validators -> django form ,自定义错误信息(欠)
创建 Django 用户:python manage.py createsuperuser
2. 根据类对数据库表中的数据进行各种操作
一对多:
a. 外检
b.
外键字段_id
c.
models.tb.object.create(name=‘root‘, user_group_id=1)
d.
userlist = models.tb.object.all()
for row in userlist:
row.id
row.user_group_id
row.user_group.caption
1、Django请求的生命周期
路由系统 -> 试图函数(获取模板+数据=》渲染) -> 字符串返回给用户
2、路由系统
/index/ -> 函数或类.as_view()
/detail/(d+) -> 函数(参数) 或 类.as_view()(参数)
/detail/(?P<nid>d+) -> 函数(参数) 或 类.as_view()(参数)
/detail/ -> include("app01.urls")
/detail/ name=‘a1‘ -> include("app01.urls")
- 视图中:reverse
- 模板中:{% url "a1" %}
3、视图
FBV:函数
def index(request,*args,**kwargs):
..
CBV:类
class Home(views.View):
def get(self,reqeust,*args,**kwargs):
..
获取用户请求中的数据:
request.POST.get
request.GET.get
reqeust.FILES.get()
# checkbox,
........getlist()
request.path_info
文件对象 = reqeust.FILES.get()
文件对象.name
文件对象.size
文件对象.chunks()
# <form 特殊的设置></form>
给用户返回数据:
render(request, "模板的文件的路径", {‘k1‘: [1,2,3,4],"k2": {‘name‘: ‘张扬‘,‘age‘: 73}})
redirect("URL")
HttpResponse(字符串)
4、模板语言
render(request, "模板的文件的路径", {‘obj‘: 1234, ‘k1‘: [1,2,3,4],"k2": {‘name‘: ‘张扬‘,‘age‘: 73}})
<html>
<body>
<h1> {{ obj }} </h1>
<h1> {{ k1.3 }} </h1>
<h1> {{ k2.name }} </h1>
{% for i in k1 %}
<p> {{ i }} </p>
{% endfor %}
{% for row in k2.keys %}
{{ row }}
{% endfor %}
{% for row in k2.values %}
{{ row }}
{% endfor %}
{% for k,v in k2.items %}
{{ k }} - {{v}}
{% endfor %}
</body>
</html>
5、ORM
a. 创建类和字段
class User(models.Model):
age = models.IntergerFiled()
name = models.CharField(max_length=10)#字符长度
Python manage.py makemigrations
python manage.py migrate
# settings.py 注册APP
b. 操作
增
models.User.objects.create(name=‘qianxiaohu‘,age=18)
dic = {‘name‘: ‘xx‘, ‘age‘: 19}
models.User.objects.create(**dic)
obj = models.User(name=‘qianxiaohu‘,age=18)
obj.save()
删
models.User.objects.filter(id=1).delete()
改
models.User.objects.filter(id__gt=1).update(name=‘alex‘,age=84)
dic = {‘name‘: ‘xx‘, ‘age‘: 19}
models.User.objects.filter(id__gt=1).update(**dic)
查
models.User.objects.filter(id=1,name=‘root‘)
models.User.objects.filter(id__gt=1,name=‘root‘)
models.User.objects.filter(id__lt=1)
models.User.objects.filter(id__gte=1)
models.User.objects.filter(id__lte=1)
models.User.objects.filter(id=1,name=‘root‘)
dic = {‘name‘: ‘xx‘, ‘age__gt‘: 19}
models.User.objects.filter(**dic)
v1 = models.Business.objects.all()
# QuerySet ,内部元素都是对象
# QuerySet ,内部元素都是字典
v2 = models.Business.objects.all().values(‘id‘,‘caption‘)
# QuerySet ,内部元素都是元组
v3 = models.Business.objects.all().values_list(‘id‘,‘caption‘)
# 获取到的一个对象,如果不存在就报错
models.Business.objects.get(id=1)
对象或者None = models.Business.objects.filter(id=1).first()
外键:
v = models.Host.objects.filter(nid__gt=0)
v[0].b.caption ----> 通过.进行跨表
外键:
class UserType(models.Model):
caption = models.CharField(max_length=32)
id caption
# 1,普通用户
# 2,VIP用户
# 3, 游客
class User(models.Model):
age = models.IntergerFiled()
name = models.CharField(max_length=10)#字符长度
# user_type_id = models.IntergerFiled() # 约束,
user_type = models.ForeignKey("UserType",to_field=‘id‘) # 约束,
name age user_type_id
# 张扬 18 3
# 张A扬 18 2
# 张B扬 18 2
position:fixed absolute relative
Ajax
$.ajax({
url: ‘/host‘,
type: "POST",
data: {‘k1‘: 123,‘k2‘: "root"},
success: function(data){
// data是服务器端返回的字符串
var obj = JSON.parse(data);
}
})
建议:永远让服务器端返回一个字典
return HttpResponse(json.dumps(字典))
多对多:
创建多对多:
方式一:自定义关系表
class Host(models.Model):
nid = models.AutoField(primary_key=True)
hostname = models.CharField(max_length=32,db_index=True)
ip = models.GenericIPAddressField(protocol="ipv4",db_index=True)
port = models.IntegerField()
b = models.ForeignKey(to="Business", to_field=‘id‘)
# 10
class Application(models.Model):
name = models.CharField(max_length=32)
# 2
class HostToApp(models.Model):
hobj = models.ForeignKey(to=‘Host‘,to_field=‘nid‘)
aobj = models.ForeignKey(to=‘Application‘,to_field=‘id‘)
# HostToApp.objects.create(hobj_id=1,aobj_id=2)
方式二:自动创建关系表
class Host(models.Model):
nid = models.AutoField(primary_key=True)
hostname = models.CharField(max_length=32,db_index=True)
ip = models.GenericIPAddressField(protocol="ipv4",db_index=True)
port = models.IntegerField()
b = models.ForeignKey(to="Business", to_field=‘id‘)
# 10
class Application(models.Model):
name = models.CharField(max_length=32)
r = models.ManyToManyField("Host")
无法直接对第三张表进行操作
obj = Application.objects.get(id=1)
obj.name
# 第三张表操作
obj.r.add(1)
obj.r.add(2)
obj.r.add(2,3,4)
obj.r.add(*[1,2,3,4])
obj.r.remove(1)
obj.r.remove(2,4)
obj.r.remove(*[1,2,3])
obj.r.clear()
obj.r.set([3,5,7])
# 所有相关的主机对象“列表” QuerySet
obj.r.all()
以上是关于Django知识点的主要内容,如果未能解决你的问题,请参考以下文章