Django学习笔记
我的Django学习笔记(一)
前期准备
1,了解项目
大纲
1.安装django
安装dango:
pip install django
c: 'python39
- python .exe- scripts
- pip.exe
- django-admin-exe【工具,创建django项即】- Lib
-内置模块
- site-packages
- openpyxl- python-docx- flask
- django【框架的源码】
2,命令行创建项目
创建django项目:django-admin startproject 项目名称
3,默认项目文件介绍:
默认项目的文件介绍:
mysite
manage-py【项目的管理,启动项目、创建app、数据管理】【不要动,常常用】
mysite
-_init__-PY
settings.py 【项目配置】【常常操作---修改】
urls.py 【RL和函数的对应关系】【常常操作--修改】
asgi.py 【接收网络请求】【不要动】
wsgi.py【接收网络请求】【不要动】
4,APP介绍
-项目
- -app,用户管理【表结构、函数、HTML模板、css]
- - app,订单管理【表结构、函数、HTL模板、css】
- - app,后台管理【表结构、函数、HTML模板、css】
- - app,网站【表结构、函数、HTML模板、css】
- app,API【表结构、函数、HTML模板、css】
注意:我们开发比较简洁,用不到多app,一般情况下,项目下创建1个app即可。
5,创建一个APP
E:\CodePractice\python代码\pythonProject\MyDjango>python manage.py startapp app01
终端输入:
python manage.py startapp app01
6,APP项目内容介绍
appo1
_init__-Pyadmin.py 【固定,不用动】django默认提供了admin后台管理。
--apps-py 【固定,不用动】app启动类
--migrations 【固定,不用动】数据库变更记录
-- _irit_-pY
--models.py 【*重要**】,对数据库操作。
--tests.PY 【固定,不用动】单元测试
- views ·pY 【重要**】,函数。
--manage. py
--mysite2
-- _init___-Pyasgi.pysettings-pyurls.py【URL->函数】
-- i wsgi.py
7,settings.py文件下编写一个请求
1,注册一个app: 'app01.apps.app01config'[settings.py]
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app01.apps.app01config'
]
2,编写URL和视图函数对应关系[urls.py文件]
from django.views import View
3.编写视图函数[views.py]
4.启动django程序:
python manage.py runserver
8,再写一个页面
---url函数
---页面函数
9,template模板
静态文件:放static文件夹下
4.3静态文件在开发过程中一般将:
·图片
. css
· js
都会当做静态文件处理。
10,连接数据库
第一步:首先打开cmd创建数据库:
create database ;
第二步:django连接数据库
在setting文件夹里面加入:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': BASE_DIR / 'db.sqlite3',
'USER': 'dbname', # 数据库名字
'PASSWARD': 'XXX', # 数据库账户名
'HOST': '127.0.0.1', # 数据库安装在哪台服务器
'PORT': '3306',#端口号
}
}
11,django操作数据库表(models.py里面创建表)
models.py文件下面写一个类:python会根据类翻译成SQL生成表
# Create your models here.
class UserInfo(models.Model):
name = models.CharField(max_length=32)
password = models.CharField(max_length=64)
age = models.IntegerField()
12,django连接数据库(models.py里面更改表后重复下面两个代码即可)
执行命令:
python manage.py makemigrations
python manage.py migrate
得到如下结果则成功
PS E:\CodePractice\python代码\pythonProject\MyDjango> python manage.py makemigrations
No changes detected
PS E:\CodePractice\python代码\pythonProject\MyDjango> python manage.py migrate
Operations to perform:
Apply all migrations: admin, app01, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying app01.0001_initial... OK
Applying app01.0002_auto_20220208_1650... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying auth.0012_alter_user_first_name_max_length... OK
Applying sessions.0001_initial... OK
PS E:\CodePractice\python代码\pythonProject\MyDjango>
13,查看创建的数据库表
C:\Users\qiqiw>mysql -u root -p
Enter password: ****
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 19
Server version: 8.0.16 MySQL Community Server - GPL
Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> show tables;
ERROR 1046 (3D000): No database selected
mysql> use runoob
Database changed
mysql> show tables;
+----------------------------+
| Tables_in_runoob |
+----------------------------+
| app01_userinfo |
| auth_group |
| auth_group_permissions |
| auth_permission |
| auth_user |
| auth_user_groups |
| auth_user_user_permissions |
| django_admin_log |
| django_content_type |
| django_migrations |
| django_session |
+----------------------------+
11 rows in set (0.01 sec)
注:
在表中新增列时,由于已存在列中可能已经有数据,所以新增列必须要指定新增列对应的数据:
1,手动输入一个值
2,设置默认值
3,允许为空
def orm(request):
# 测试orm操作
# #新建数据;类名+object.create()
Department.objects.create(title="销售部")
Department.objects.create(title="IT部")
Department.objects.create(title="运营部")
return HttpResponse("成功")
通过上面操作可以在UserInfo和class Department中增加数据库中的值
class UserInfo(models.Model):
name = models.CharField(max_length=32, verbose_name='测试项目名称')
password = models.CharField(max_length=64, verbose_name='版本')
age = models.IntegerField()
class Department(models.Model):
title = models.CharField(max_length=16)
mysql> select * from runoob
-> select * from runoob;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'select * from runoob' at line 2
mysql> select * from runoob;
ERROR 1146 (42S02): Table 'runoob.runoob' doesn't exist
mysql> select * from Tables_in_runoob;
ERROR 1146 (42S02): Table 'runoob.tables_in_runoob' doesn't exist
mysql> select * from appo1_userinfo;
ERROR 1146 (42S02): Table 'runoob.appo1_userinfo' doesn't exist
mysql> desc runoob;
ERROR 1146 (42S02): Table 'runoob.runoob' doesn't exist
mysql> desc Tables_in_runoob;
ERROR 1146 (42S02): Table 'runoob.tables_in_runoob' doesn't exist
mysql> desc app01_department;#app01是文件夹,department是类名字即数据库名字
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | bigint(20) | NO | PRI | NULL | auto_increment |
| title | varchar(16) | NO | | NULL | |
+-------+-------------+------+-----+---------+----------------+
2 rows in set (0.01 sec)
mysql> desc app01_userinfo;#app01是文件夹,userinfo是类名字即数据库名字
+----------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+----------------+
| id | bigint(20) | NO | PRI | NULL | auto_increment |
| name | varchar(32) | NO | | NULL | |
| password | varchar(64) | NO | | NULL | |
| age | int(11) | NO | | NULL | |
+----------+-------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
mysql> select * from app01_userinfo;
+----+---------+----------+-----+
| id | name | password | age |
+----+---------+----------+-----+
| 1 | wupeiqi | 123 | 19 |
| 2 | wupeiqi | 123 | 19 |
| 3 | wupeiqi | 123 | 19 |
| 4 | wupeiqi | 123 | 19 |
| 5 | wupeiqi | 123 | 19 |
+----+---------+----------+-----+
11 rows in set (0.00 sec)
###14,views.py文件下
对数据库的增删改查操作
from app01.models import Department, UserInfo
def orm(request):
# 测试orm操作
###--1--新建数据---###
# 类名+object.create()
# Department.objects.create(title="销售部")
# Department.objects.create(title="IT部")
# Department.objects.create(title="运营部")
# UserInfo.objects.create(name="李小凤", password="123", age=19)
# UserInfo.objects.create(name="李小凤2", password="1234", age=22)
# UserInfo.objects.create(name="李小凤3", password="12345", age=23)
# ##--2--条件删除---##
UserInfo.objects.filter(id=16).delete()
# Department.objects.all().delete()
# 删除所有数据
# UserInfo.objects.all().delete()
# Department.objects.all().delete()
# ##--3--获取数据---## # all()表示获取全部数据
# data_list=[行,行,行] Queryset类型
# 数据列表=models里面类名字.objects.all()
# data_list=UserInfo.objects.all()
# for obj in data_list:
# print(obj.id,obj.name,obj.password,obj.age)
# ##---获取指定id数据---## #filter(id=17)
# data_list = UserInfo.objects.filter(id=17) # 获取全部数据
# for obj in data_list:
# print(obj.id, obj.name, obj.password, obj.age)
# row_obj = UserInfo.objects.filter(id=17).first() # 获取全部数据
# print(row_obj.id,row_obj.name,row_obj.password,row_obj.age)
# ###--4--更新数据--####
# 全部passward改为666
# UserInfo.objects.all().update(password=666)
# 指定ID更改数据
# UserInfo.objects.filter(id=15).update(age=999)
# UserInfo.objects.filter(name="李小凤1").update(age=123)
return HttpResponse("运行成功")
用户管理案例教程
一,搭建环境
1,命令行创建项目和app
Django-admin startproject mysite #项目名称
python manage.py startapp app01
2,settings.py文件下面创建一个请求
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app01.apps.App01Config' # 新增加 App01Config来自于apps.py
]
3,urls.py编写
from django.contrib import admin
from django.urls import path
from app01 import views
urlpatterns = [
# path('admin/', admin.site.urls),
path('lxf/', views.index),
]
4,views.py编写函数
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
def index(request):
return HttpResponse("欢迎使用")
5,环境运行检查是否搭建成功
python manage.py runserver
二,开始项目
1,写一个urls.py
from django.contrib import admin
from django.urls import path
from app01 import views
urlpatterns = [
# path('admin/', admin.site.urls),
# path('lxf/', views.index),
path('lxf/', views.info_list),
]
2,views.py定义一个函数info_list()
from app01.models import Department, UserInfo
def info_list(request):
# 获取数据库中所有数据信息
data_list = UserInfo.objects.all()
print(data_list)
# for item in data_list:
# item.id,item.name,item.password
return render(request, "info_list.html",
{"data_list":data_list})
3,数据库创建--------省略
DATABASES = {
'default':
{
'ENGINE': 'django.db.backends.mysql', # 数据库引擎
'NAME': 'runoob', # 数据库名称
'HOST': 'localhost', # 数据库地址,本机 ip 地址 127.0.0.1
'PORT': '3306', # 端口
'USER': 'root', # 数据库用户名
'PASSWORD': 'root', # 数据库密码
}
}
4,template里面写一个前端HTM文件,并使用模板语法
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>info列表</h1>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>密码</th>
<th>年龄</th>
</tr>
</thead>
<tbody>
{% for obj in data_list %}
<tr>
<td>{{obj.id}}</td>
<td>{{obj.name}}</td>
<td>{{obj.password}}</td>
<td>{{obj.age}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>