django创建项目
先创建一个文件夹用来放django的项目,我这里是My_Django_it
之后打开到该文件下,并用下面的指令来创建myDjango1项目
D:\>cd My_Django_it
D:\My_Django_it>"D:\zzu_it\Django_learn\Scripts\django-admin.exe" startproject myDjango1
D:\My_Django_it>
文件介绍
APP
类似蓝图
模块化
python manage.py startapp app01
快速项目
在myDjango2中的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",
]
最后一句加上"app01.apps.App01Config",
编写URL和视图的关系
运行项目
python manage.py migrate
bug: 若出现下面报错
You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
Error: You don't have permission to access that port.
说明端口被占用了,很可能是酷狗占用了,只要关闭酷狗就行了
后端渲染
def user_list(request):
return render(request,"user_list.html")
加载静态界面
记得上面加入{% load static %}
模板语法
def tpl(request):
name="李四"
roles=["管理员","CEO","保安"]
user_info={"name":"李明","salary":10000,"role":"CEO"}
data_list=[
{"name": "李明", "salary": 10000, "role": "CEO"},
{"name": "王五", "salary": 10000, "role": "CEO"},
{"name": "李四", "salary": 10000, "role": "CEO"},
{"name": "赵一", "salary": 10000, "role": "CEO"}
]
return render(request,"tpl.html",{"n1":name,"n2":roles,"n3":user_info,"n4":data_list})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>模板语法的学习</h1>
<div>{{ n1 }}</div>
<div>{{ n2 }}</div>
<div>{{ n2.0 }}</div>
<div>{{ n2.1 }}</div>
<div>{{ n2.2 }}</div>
<div>
{% for item in n2 %}
<span>{{ item }}</span>
{% endfor %}
</div>
<div>
{{ n3.name }}
{{ n3.salary}}
{{ n3.role }}
</div>
<ul>
{% for item,v in n3.items %}
<li>{{ item }}:{{ v }}</li>
{% endfor %}
</ul>
<hr>
{{ n4.1.name }}
<ul>
{% for item in n4 %}
{% for k,v in item.items %}
<li>{{ k }}:{{ v }}</li>
{% endfor %}
{% endfor %}
</ul>
</body>
</html>
通过爬虫显示数据
在news函数中如下
def news(req):
#用爬虫获取新闻
# 向http://www.chinaunicom.com.cn/api/article/NewsByIndex/2/2023/07/news发送请求
import requests
res=requests.get("http://www.chinaunicom.com.cn/api/article/NewsByIndex/2/2023/07/news",headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36 Edg/115.0.1901.183"})
print(res)
data_list=res.json()
print(data_list)
return render(req,"news.html")
其中如果报错Expecting value: line 1 column 1 (char 0)
,找到上图User-Agent的位置,加入到requests参数中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>新闻</title>
</head>
<body>
<h1>新闻中心</h1>
<ul>
{% for news in news_list %}
<li>新闻标题:{{ news.news_title }}</li>
<li>时间:{{ news.post_time }}</li>
{% endfor %}
</ul>
</body>
</html>
请求与响应
def something(request):
# request 是一个对象,浏览器发的所有数据
print(request.method)
print(request.GET)
print(request.POST)
# HttpResponse返回里面的字符串
#return HttpResponse("返回")
#渲染
#return render(request,"something.html",{"title":"1212"})
#重定向
#return redirect("https://www.baidu.com")
登录
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>用户登录</h1>
<form action="/login/" method="post">
{% csrf_token %}
<input type="text" name="user" placeholder="用户名">
<input type="password" name="pwd" placeholder="密码">
<input type="submit" value="提交">
<span style="color:red;">{{ error_msg }} </span>
</form>
</body>
</html>
上面一定要加上 {% csrf_token %}
def login(request):
if request.method=="GET":
return render(request,"login.html")
print(request.POST)
username = request.POST.get("user")
password = request.POST.get("pwd")
print(username,password)
if username=="root" and password=="123":
#return HttpResponse("登录成功")
return redirect("http://www.chinaunicom.com.cn")
#return HttpResponse("登录失败")
return render(request,"login.html",{"error_msg":"用户名或密码错误"})
数据库
安装外部库
pip install mysqlclient
ORM
- 创建表,修改,删除(不能创建数据库)
- 操作表中的数据
创建数据库
- 启动MySQL
- 自带工具创建数据库
在cmd中进入mysql -u root -p进入
创建数据库
create database django_learn2 DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
查看数据库
show databases
也可以通过Navicat中创建数据库
在setting.py中创建数据库参数
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME':'Django_learn',
'USER': 'root',
'PASSWORD': '200625',
'HOST': '127.0.0.1',
'PORT': 3306,
}
}
在models.py中
class UserInfo(models.Model):
#表名 app01_userInfo
name = models.CharField(max_length=32)
password=models.CharField(max_length=32)
age=models.IntegerField()
在命令框中执行如下
python manage.py makemigrations
python manage.py migrate
在cmd中选择数据库
use django_learn
显示表
show tables
显示表中的变量
desc app01_userinfo
若在原有的数据库中添加新的变量需要再次执行如下
python manage.py makemigrations
python manage.py migrate
并且在models.py中添加上默认值
class UserInfo(models.Model):
#表名 app01_userInfo
name = models.CharField(max_length=32)
password=models.CharField(max_length=32)
age=models.IntegerField()
size=models.IntegerField(default=2)
增删改查
增
class Department(models.Model):
title=models.CharField(max_length=16)
def orm(request):
# 测试表中的数据
Department.objects.create(title="销售部")
Department.objects.create(title="运营部")
Department.objects.create(title="研发部")
return HttpResponse("success")
删除
Department.objects.filter(title="运营部").delete()
Department.objects.all().delete()#全删
获取数据
data_list=Department.objects.all()#QuerySet类型 类似列表
print(data_list)
输出结果
<QuerySet [<Department: Department object (1)>, <Department: Department object (3)>]>
获取单独的元素
for obj in data_list:
print(obj.id,obj.title)
1 销售部
3 研发部
# data = Department.objects.filter(id=1)#依然是列表类型
# for obj in data:
# print(obj.title)
data = Department.objects.filter(id=1).first()#元素类型
print(data.title)
销售部
更新数据
Department.objects.all().update(title="销售部")
Department.objects.filter(id=1).update(title="研发部")
用户管理案例
###展示数据
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>表格</h1>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>AGE</th>
<th>SIZE</th>
</tr>
</thead>
<tbody>
{% for obj in data_list %}
<tr>
<td>{{ obj.id }}</td>
<td>{{ obj.name}}</td>
<td>{{obj.age}}</td>
<td>{{obj.size}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
def info_list(request):
# 获取用户的所有信息
data_list = UserInfo.objects.all()
print(data_list)
return render(request,"info_list.html",{"data_list":data_list})
添加用户
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>添加用户</h1>
<form method="post" action="/info/add">
{% csrf_token %}
<input type="text" name = "user" placeholder="用户名">
<input type="password" name = "pwd" placeholder="密码">
<input type="text" name = "age" placeholder="年龄">
<input type="text" name = "size" placeholder="大小">
<input type="submit" value="提交">
</form>
</body>
</html>
def info_add(request):
if request.method=="GET":
return render(request,"info_add.html")
user=request.POST.get('user')
pwd=request.POST.get('pwd')
age=request.POST.get('age')
size=request.POST.get('size')
UserInfo.objects.create(name=user,password=pwd,age=age,size=size)
#return HttpResponse("添加成功")
return redirect("/info/list")#自动拼接
删除
def info_delete(request):
nid=request.GET.get("nid")
UserInfo.objects.filter(id=nid).delete()
return redirect("/info/list")
在用户管理界面中增加文章来源:https://www.toymoban.com/news/detail-614687.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>表格</h1>
<a href="/info/add">添加</a>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>AGE</th>
<th>SIZE</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for obj in data_list %}
<tr>
<td>{{ obj.id }}</td>
<td>{{ obj.name }}</td>
<td>{{obj.age }}</td>
<td>{{obj.size }}</td>
<td><a href="/info/delete/?nid={{ obj.id }}">删除</a></td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
文章来源地址https://www.toymoban.com/news/detail-614687.html
到了这里,关于django学习笔记(1)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!