一、Django的配置静态文件(settings)

STATIC_URL = '/static/'    #引用名
STATICFILES_DIRS = (
os.path.join(BASE_DIR,"statics"), # 实际名 ,即实际文件夹的名字
)

django对引用名和实际名进行映射,引用时,只能按照引用名来,不能按实际名去找

#<script src="/statics/jquery-3.1.1.js"></script>
#------error-----不能直接用,必须用STATIC_URL = '/static/':
#<script src="/static/jquery-3.1.1.js"></script>

推荐方式:

STATIC_URL = '/static/'
前端:
{% load staticfiles %}
<script src={% static "jquery-1.8.2.min.js" %}></script>

二、Django URL(路由系统)

 1、url  --- 视图

urlpatterns = [
url(正则表达式, views视图函数,参数,别名),
]
def url(regex, view, kwargs=None, name=None):

kwargs:传给视图的默认参数(字典形式)

name:别名xxx

比如:

<form action="{% url 'xxx' %}" class="form-horizontal" method="post">

就可以提交到该路由

路由一旦匹配成功就不匹配下面的url了,所以最好加上$结尾符

2、无命名分组和有命名分组

url(r'^articles/([0-9]{4})/$', views.year_archive),  #no_named group
url(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive),#named group

有命名分组的year为视图的关键字参数 

注意:同源策略

3、路由分发

url(r'^article/',include(("article.urls","article"),namespace="article")),
def include(arg, namespace=None):
app_name = None
if isinstance(arg, tuple):
# Callable returning a namespace hint.
try:
urlconf_module, app_name = arg
except ValueError:
if namespace:
raise ImproperlyConfigured(
'Cannot override the namespace for a dynamic module that '
'provides a namespace.'
)
raise ImproperlyConfigured(
'Passing a %d-tuple to include() is not supported. Pass a '
'2-tuple containing the list of patterns and app_name, and '
'provide the namespace argument to include() instead.' % len(arg)
)
else:
# No namespace hint - use manually provided namespace.
urlconf_module = arg if isinstance(urlconf_module, str):
urlconf_module = import_module(urlconf_module)
patterns = getattr(urlconf_module, 'urlpatterns', urlconf_module)
app_name = getattr(urlconf_module, 'app_name', app_name)
if namespace and not app_name:
raise ImproperlyConfigured(
'Specifying a namespace in include() without providing an app_name '
'is not supported. Set the app_name attribute in the included '
'module, or pass a 2-tuple containing the list of patterns and '
'app_name instead.',
)
namespace = namespace or app_name
# Make sure the patterns can be iterated through (without this, some
# testcases will break).
if isinstance(patterns, (list, tuple)):
for url_pattern in patterns:
pattern = getattr(url_pattern, 'pattern', None)
if isinstance(pattern, LocalePrefixPattern):
raise ImproperlyConfigured(
'Using i18n_patterns in an included URLconf is not allowed.'
)
return (urlconf_module, app_name, namespace)
url(r'^article/',include(("appxxx.urls","app_name"),namespace="appxxx")),

app_name和namespace区别参考https://www.jianshu.com/p/404500a0408a  

三、Django views(视图函数)

django.http中有两个重要的对象HttpRequest、HttpResponse

注意一个常用的方法:request.POST.get('')

四、模板语法

HTML代码+逻辑控制代码

1、变量 --- {{ xxx }}

①深度变量的查找 ---万能的句点号

[1]、访问列表索引 {{ items.2 }}

[2]、访问字典的值 {{ person.name }}

[3]、访问对象的属性 {{ date.year }} date=datetime.date(1993,5,2)

[4]、访问自定义类对象的属性 {{ person.firstname }}

[5]、引用对象的方法 {{ var.upper }} ---注意:只能调用不需要参数的方法

②变量的过滤器 ---filter

语法格式:      {{ obj | filter:param }}

 # 1  add          :   给变量加上相应的值
#
# 2 addslashes : 给变量中的引号前加上斜线
#
# 3 capfirst : 首字母大写
#
# 4 cut : 从字符串中移除指定的字符
#
# 5 date : 格式化日期字符串
#
# 6 default : 如果值是False,就替换成设置的默认值,否则就是用本来的值
#
# 7 default_if_none: 如果值是None,就替换成设置的默认值,否则就使用本来的值 #实例: #value1="aBcDe"
{{ value1|upper }}<br> #value2=5
{{ value2|add:3 }}<br> #value3='he llo wo r ld'
{{ value3|cut:' ' }}<br> #import datetime
#value4=datetime.datetime.now()
{{ value4|date:'Y-m-d' }}<br> #value5=[]
{{ value5|default:'空的' }}<br> #value6='<a href="#">跳转</a>' {{ value6 }} {% autoescape off %}
{{ value6 }}
{% endautoescape %} {{ value6|safe }}<br> {{ value6|striptags }} #value7='1234'
{{ value7|filesizeformat }}<br>
{{ value7|first }}<br>
{{ value7|length }}<br>
{{ value7|slice:":-1" }}<br> #value8='http://www.baidu.com/?a=1&b=3'
{{ value8|urlencode }}<br>
value9='hello I am yuan'

2、标签(tag) ---{% tags %}

①{% if %}

②{% for %}

不支持break,也不支持continue,但内置了一个forloop变量,forloop.counter---计数从1开始

③{% csrf_token %}

注意:使用render_to_response方法,不会生效

④{% url %}

⑤{% with total=gjdgfdlkgjkdjgjgisdgdsg %}{{ total }}{% endwith %}

⑥{% verbatim %} ---禁止render

⑦{% load %}

3、自定义filter和simple_tag

①在app中创建templatetags模块(必须的)

②创建任意 .py 文件,如:my_tags.py

from django import template
from django.utils.safestring import mark_safe register = template.Library() #register的名字是固定的,不可改变 @register.filter
def filter_multi(v1,v2):
return v1 * v2 @register.simple_tag
def simple_tag_multi(v1,v2):
return v1 * v2 @register.simple_tag
def my_input(id,arg):
result = "<input type='text' id='%s' class='%s' />" %(id,arg,)
return mark_safe(result)

③在使用自定义simple_tag和filter的html文件中导入之前创建的 my_tags.py :{% load my_tags %}

④使用simple_tag和filter(如何调用)

-------------------------------.html
{% load xxx %} #首行 # num=12
{{ num|filter_multi:2 }} # {{ num|filter_multi:"[22,333,4444]" }} {% simple_tag_multi 2 5 %} 参数不限,但不能放在if for语句中
{% simple_tag_multi num 5 %}

⑤在settings中的INSTALLED_APPS配置当前app,不然django无法找到自定义的simple_tag.

注意:

filter可以用在if等语句后,simple_tag不可以

{% if num|filter_multi:30 > 100 %}
{{ num|filter_multi:30 }}
{% endif %}

4、include和extends

①{% include xxx %}

②{% extends xxx %} ---必须在首行

{% block xxx %}{% endblock %}

注:{{ block.super }}在上级代码块基础上添加内容

五、Models

django.db.models.Model类

关系:一对一(foreign key + unique) 、一对多(foreign key)、多对多(两个foreign key),外键默认关联的是主键

注:关于 Class Meta用法可参考https://blog.csdn.net/qq_41763291/article/details/80229977http://iluoxuan.iteye.com/blog/1703061

1、模型常用的字段类型参数

①CharFiled等,参考http://www.cnblogs.com/wt869054461/p/4014271.html

2、Filed重要参数

参考①链接

3、表的操作(增删改查)

①增

from app01.models import *

    #create方式一:   Author.objects.create(name='Alvin')

    #create方式二:   Author.objects.create(**{"name":"alex"})

    #save方式一:     author=Author(name="alvin")
author.save() #save方式二: author=Author()
author.name="alvin"
author.save()

以下表名的意思为models中的类名

[1]、一对多关系

可以直接用 外键字段_id    如 表名.objects.create(外键字段_id=2,...)  绑定外键表当中id=2的行对象

[2]、多对多

A、第三张表通过models.ManyToManyField()创建的

a、正向添加:

     外键表对象f1=外键表名.objects.get(id=1)

     外键表对象f2=外键表名.objects.get(id=2)

     表对象obj=表名.objects.get(id=1)

     obj.外键字段.add(f1,f2)    ---等同于 obj.外键字段.add(*[f1,f2])  

b、反向添加:

     表对象obj=表名.objects.get(id=1)

     外键表对象f=外键表名.objects.get(id=2)

     f.表名小写_set.add(obj)

也就是说  表对象obj.外键字段.add(xxx)   也可以   外键表对象f.表名小写_set.add(obj)

B、第三张表自己创建的

类似于一对多的方式

②删

delete()  ---级联删除

多对多关系

remove()、clear()

③改

update()为QuerySet对象的方法

save()更新所有列,效率低,而update()只更新更改的列

多对多的更改,先清空clear()再添加add(xxx)

④查

filter、all、get---没有匹配的报错、values---字典、value_list---元组

4、QuerySet惰性机制

只有当调用QuerySet时才执行sql

cache避免重复查询

iterator()适合操作大的queryset,节省内存,但需重复遍历

5、对象查询、单表条件查询,多表条件关联查询

#--------------------对象形式的查找--------------------------
# 正向查找
ret1=models.Book.objects.first()
print(ret1.title)
print(ret1.price)
print(ret1.publisher)
print(ret1.publisher.name) #因为一对多的关系所以ret1.publisher是一个对象,而不是一个queryset集合 # 反向查找
ret2=models.Publish.objects.last()
print(ret2.name)
print(ret2.city)
#如何拿到与它绑定的Book对象呢?
print(ret2.book_set.all()) #ret2.book_set是一个queryset集合 #---------------了不起的双下划线(__)之单表条件查询---------------- # models.Tb1.objects.filter(id__lt=10, id__gt=1) # 获取id大于1 且 小于10的值
#
# models.Tb1.objects.filter(id__in=[11, 22, 33]) # 获取id等于11、22、33的数据
# models.Tb1.objects.exclude(id__in=[11, 22, 33]) # not in
#
# models.Tb1.objects.filter(name__contains="ven")
# models.Tb1.objects.filter(name__icontains="ven") # icontains大小写不敏感
#
# models.Tb1.objects.filter(id__range=[1, 2]) # 范围bettwen and
#
# startswith,istartswith, endswith, iendswith, #----------------了不起的双下划线(__)之多表条件关联查询--------------- # 正向查找(条件) # ret3=models.Book.objects.filter(title='Python').values('id')
# print(ret3)#[{'id': 1}] #正向查找(条件)之一对多 ret4=models.Book.objects.filter(title='Python').values('publisher__city')
print(ret4) #[{'publisher__city': '北京'}] #正向查找(条件)之多对多
ret5=models.Book.objects.filter(title='Python').values('author__name')
print(ret5)
ret6=models.Book.objects.filter(author__name="alex").values('title')
print(ret6) #注意
#正向查找的publisher__city或者author__name中的publisher,author是book表中绑定的字段
#一对多和多对多在这里用法没区别 # 反向查找(条件) #反向查找之一对多:
ret8=models.Publisher.objects.filter(book__title='Python').values('name')
print(ret8)#[{'name': '人大出版社'}] 注意,book__title中的book就是Publisher的关联表名 ret9=models.Publisher.objects.filter(book__title='Python').values('book__authors')
print(ret9)#[{'book__authors': 1}, {'book__authors': 2}] #反向查找之多对多:
ret10=models.Author.objects.filter(book__title='Python').values('name')
print(ret10)#[{'name': 'alex'}, {'name': 'alvin'}] #注意
#正向查找的book__title中的book是表名Book
#一对多和多对多在这里用法没区别

6、聚合查询和分组查询

aggregate()、annotate()

7、F查询和Q查询

本文参考文献:https://www.cnblogs.com/yuanchenqi/articles/6083427.html

Django_tips的更多相关文章

随机推荐

  1. classic code review

    package dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSe ...

  2. centos7通过yum安装mysql8

    1.检查是否安装mariadb rpm -qa | grep mariadb 若有会显示 mariadb-libs-5.5.56-2.el7.x86_64 2.卸载mariadb rpm -e --n ...

  3. macbook远程连接报错no matching cipher found

    在.ssh/目录下添加config文件 Host xxx.xxx.xxx.xxx Ciphers 3des-cbc KexAlgorithms +diffie-hellman-group1-sha1 ...

  4. [随笔][Java][总结][java 类型系统]

    java 的类型系统大体分为两类,对象和基本类型.java使用静态类型检查来保证类型安全.每个变量在使用之前需要声明.非静态类型的语言不要求变量在使用之前进行声明. 基本数据类型 java的基本类型不 ...

  5. saltstack总结-2018-0620

    以下结论 结论1由于minion配置文件里能配置的只有master的IP和master的ret_port,而无法指定master的publish_port因此minion获取的master的publi ...

  6. 当yum安装出现Error: Package: glibc-headers .....时

    环境 CentOS Linux release 7.4.1708 (Core)   当使用yum源安装时,出现以下报错 Error: Package: glibc-headers-.el7_4..x8 ...

  7. 关于C6678的网口问题

    1.C6678 Keystone1架构的GbE switch subsystem如图所示: 2.从图中可以看到MAC层与物理层PHY芯片的连接接口是由SGMII+SerDES构成,SGMII是以太网M ...

  8. .Net Core跨平台应用研究-HelloArm(串口篇)

    引言 为了验证采用dotnet core技术开发的物联网设备数据采集接入服务应用是否能在高性价比的linux嵌入式平台运行,针对dotnet core应用程序进行嵌入式linux环境的发布部署运行验证 ...

  9. [转][C#]ImageHelper

    { internal static class ImageHelper { public static Bitmap CloneBitmap(Image source) { if (source == ...

  10. [UE4]瞬移之后的朝向

    一.Set Actor Rotation:设置绝对朝向:Set Actor Relative Rotation:设置相对朝向 二.瞬移以后,角色的朝向和相机的朝向是不一样的,和头显的朝向不是同一个朝向 ...