Day1
一、安装虚拟环境指令
pip3 install virtualenv
pip3 install virtualenvwrapper
mkdir $HOME/.virtualenvs
vim ~/.bashrc
export WORKON_HOME=$HOME/.virtualenvs
source ~/.local/bin/virtualenvwrapper.sh
VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
source ~/.bashrc
二、虚拟环境创建进入与退出
mkvirtualenv myenv -p /usr/bin/python3
python+exit()
deactivate
workon myenv
deactivate
python+exit()
三、在虚拟环境中安装模块
workon myenv
pip freeze
pip install django==1.11.7
pip freeze
pip list
四、在虚拟环境中创建项目
django-admin startproject HelloDjango
ls
tree
sudo apt install tree
tree
cd HelloDjango/
gedit ~/.local/bin/virtualenvwrapper.sh
五、在虚拟环境创建应用程序
python3 manage.py startapp App
python3 manage.py runserver
ctrl+C
六、在pycharm中配置环境
open pycharm -> file -> setting -> Project:HelloDjango -> Python Interpreter
下拉列表 -> show all -> '+' -> /home/cj/.virtualenvs/myenv/bin/python
~~~~windows用pycharm创建django项目从这里开始~~~~
terminal -> python3 manage.py makemigrations
terminal -> python3 manage.py migrate
七、在pycharm中创建APP
terminal -> python3 manage.py startapp Day_1
在HelloDjango中的setting.py 中INSTALLED_APPS列表加入‘Day_1’
在HelloDjango中的urls.py 中urlpatterns列表加入url(r'^module_one/',include('Day_1.urls'))
右击Day_1的 templates文件夹选择mark directionary as -> mark as template folder
八、在pycharm中配置数据库
(1)sqlite3
右边database,+,data source,SQLite,本项目的db.sqlite3,对话框下边download驱动,确定
terminal -> python3 manage.py makemigrations
terminal -> python3 manage.py migrate
(2)mysql
先下载mysql,见linux学习笔记,root账号密码是abccba
右边database,+,data source,Mysql,root,abccba,myenvHelloDjango,对话框下边download驱动,确定
在HelloDjango下的__init__.py中
在HelloDjango下的setting.py中
'ENGINE': 'django.db.backends.mysql',
'NAME': 'myenvHelloDjango',
'USER': 'cj',
'PASSWORD': 'Cj1234567~',
'HOST': '127.0.0.1',
'PORT': '3306',
打开控制台
terminal -> python3 manage.py makemigrations
terminal -> python3 manage.py migrate
九、在pycharm 中添加数据表
在models.py文件写
from django.db import models
class Student(models.Model):
s_name = models.CharField(max_length=16)
s_age = models.IntegerField(default=1)
terminal -> python3 manage.py makemigrations
terminal -> python3 manage.py migrate
十、数据库的增删改查
def stu(request):
#增
stu = Student()
stu.s_name = 'Tom' + str(random.randint(1, 100))
stu.save()
#查
stus = Student.objects.all()
for i in stus:
print(i.s_name)
#改
stu2 = Student.objects.get(s_age=10)
stu2.s_name=stu2.s_name[:3]+str(random.randint(1, 100))
stu2.save()
print('read'+stu2.s_name)
#删(我先创建一个)
# stu3 = Student()
# stu3.s_name = 'GG'
# stu3.save()
# stu4 = Student.objects.get(s_name='GG')
# stu4.delete()
# stu4.save()
return render(request, 'stu.html')
十一、读HTML内容
def gogogo(request): student=Student111.objects.get(pk=1) grade=student.s_grade return HttpResponse('Grade %s'%grade.g_name) def upupup(request): grade=Grade111.objects.get(pk=1) students=grade.student111_set.all() context={ 'students':students } return render(request,'student_list111.html',context=context)
def http(request): three_index = loader.get_template('three_index.html') context = { "student_name": "Sunck" } result = three_index.render(context=context) print(result) return HttpResponse(result)
十二、shell调试
python3 manage.py shell
from Day_2.models import Student
stu = Student()
stu.s_name = 'Tom' + str(random.randint(1, 100))
stu.save()
十三、使用外键
在models.py文件中
class Grade111(models.Model):
g_name = models.CharField(max_length=32)
class Student111(models.Model):
s_name = models.CharField(max_length=16)
s_grade = models.ForeignKey(Grade111,default=1,on_delete=models.CASCADE)
makemigrations与migrate
在view.py中
def gogogo(request):
student=Student111.objects.get(pk=1)
grade=student.s_grade
return HttpResponse('Grade %s'%grade.g_name)
def upupup(request):
grade=Grade111.objects.get(pk=1)
students=grade.student111_set.all()
context={
'students':students
}
return render(request,'student_list111.html',context=context)
在student_list111.html中
Title
{% for i in students %}
- {
{i.s_name}}
{% endfor %}
Day2:
字段类型(models.后接的类型)
AutoField
CharField(max_length=字符长度)
TextField
IntegerField
DecimalField(max_digits=None, decimal_places=None)
FloatField
BooleanField
NullBooleanField
DateField([auto_now=False, auto_now_add=False])
TimeField
DataTimeField
FileField
ImageField
字段选项(models.类型()中括号的字段)
null
blank
db_column
db_index
default
primary_key
unique
关系
ForeignKey
ManyToManyField
OneToOneField
过滤器类型
all()全部
filter()选择
exclude()剔除
order_by()排序
values()一条数据是一个字典,返回列表,用于json转换
first()第一个
last()最后一个
count()计算个数(其实可以之后再用len)
exists()判断查询集是否有数据(其实可以之后再用len)
get()返回单个对象(找不到或找到多个都抛异常,不建议用)
【这里要说一下扔过去html用table显示时的写法:】
【如果用values就是扔个list过去,然后for出一条信息,然后{
{i.attr}}】
【如果不用values则不是扔list,但queryset可以迭代,故与list写法一样】
[x:y]可以用切片,取x到y-1部分
过滤器字段选项(可链式调用)
pk=x(主键)
attribute=x(字符串数字日期皆可用)
·数字专用
attribute__lt=x
attribute__gt=y
attribute__lte=x
attribute__gte=y
attribute__in=[a,b,c,d](在某一集合中)
·字符串专用
attribute__exact='z'(精确等于)
attribute__contains='z'(模糊等于即like%*%)
attribute__startwith='z'(以什么开始即like%*)
attribute__endwith='z'(以什么结束即like*%)
attribute__iexact='z'(忽略大小写精确等于)
attribute__icontains='z'(忽略大小写模糊等于即like%*%)
attribute__istartwith='z'(忽略大小写以什么开始即like%*)
attribute__iendwith='z'(忽略大小写以什么结束即like*%)
attribute__isnull=True(空)
attribute__isnotnull=True(非空)
·日期专用(setting.py中USE_TZ = False)
attribute__year=2010
attribute__month=10
attribute__day=10
attribute__hour=10
attribute__minute=10
attribute__second=10
attribute__week_day=10
聚合函数
x=Class.objects.aggregate(Max('id'))
x=Class.objects.aggregate(Avg('id'))
x=Class.objects.aggregate(Min('id'))
x=Class.objects.aggregate(Sum('id'))
x=Class.objects.aggregate(Count('id'))
F对象(属性比较)
x=Class.objects.filter(attr1__lt=F('attr2'))
Q对象(逻辑运算)
x=Class.objects.filter(Q(attr1__lt=5)&Q(attr2__lt=3))
状态码
2xx:请求成功
3xx:转发重定向
4xx:客户端错误
5xx:服务器错误
快捷键
ctrl+d复制本行并在下一行粘贴
shift+alt+up/down整行上移与下移(调换)
关于模型中的语法看Day1下的views.py代码实例即可
Day3:
路由规则:
urlpatterns = [
url(r'^$', index),
url(r'^hello/$', views.hello1),
url(r'^hello/(\d+)/', views.hello2),
url(r'^hello/(?P\d+)/(?P\d+)/(?P\d+)/$', views.hello3),
]
r表示不转义
^表示开始
$表示结尾
/表示路径节点结束
注意:访问http://127.0.0.1:8000/Day2/hello/22/时第三行匹配为true
但是:如果第二行是r'^hello/'则会在遍历到第二行时执行为true
上面路由的view响应函数接收参数的写法:
def hello1(request):....
def hello2(request, int1):....
def hello3(request, year, month, day):....
渲染传参:
locals()就是把全部局部变量传过去HTML,字典的key就是变量名
反向解析
·根路由url.py定义namespace
例如:url(r'^Day2/', include(('Day2.urls', 'Day2'), namespace='cj_namespace'))
·子路由url.py定义name
例如:url(r'^hello/$', views.hello1, name='cj_hello1'),
url(r'^hello/(\d+)/$', views.hello2, name='cj_hello2'),
url(r'^hello/(?P\d+)/(?P\d+)/(?P\d+)/$', views.hello3, name='cj_hello3'),
然后在href中用namespace与name
例如:hello1
hello2
hello3
错误页面:
首先在templates中重写404.html(其他状态码同理)
然后在setting.py关掉debug模式
request
get:在上面得到路由后,再追加参数,例如?params=xxx¶ms=yyy
post:在html中的form设定method='post',然后按submit后就是POST请求了
META:可以查到客户端元信息