Model模型的实战操作笔记
1. 创建数据库和表(若是执行表迁移,可跳过下面操作)
- 进入MySQL数据库创建数据库:mytest
进入数据库创建数据表:myapp_users
CREATE TABLE `myapp_users` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(32) NOT NULL, `age` tinyint(3) unsigned NOT NULL DEFAULT '20', `phone` varchar(16) DEFAULT NULL, `addtime` datetime(6) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8
添加几条测试数据
2. 创建项目myweb和应用myapp
# 创建项目框架myweb
$ django-admin startproject myweb
$ cd myweb
# 在项目中创建一个myapp应用
$ python3.6 manage.py startapp myapp
# 创建模板目录
$ mkdir templates
$ mkdir templates/myapp
$ cd ..
$ tree myweb
myweb
├── myweb
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── manage.py
├── myapp
│ ├── admin.py
│ ├── apps.py
│ ├── __init__.py
│ ├── models.py
│ ├── tests.py
│ └── views.py
└── templates
└── myapp
3. 执行数据库连接配置,网站配置
3.1 编辑myweb/myweb/__init__.py
文件,添加Pymysql的数据库操作支持
import pymysql
pymysql.install_as_MySQLdb()
3.2 编辑myweb/myweb/settings.py文件,配置数据库连接
...
#配置自己的服务器IP地址
ALLOWED_HOSTS = ['localhost','127.0.0.1','172.16.142.129']
...
#添加自己应用
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp',
]
...
# 配置模板路径信息
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',
],
},
},
]
...
# 数据库连接配置
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mytest',
'USER': 'root',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': '3306',
}
...
4. 定义Model类
4.1 编辑myweb/myapp/models.py
from django.db import models
class Users(models.Model):
name = models.CharField(max_length=32)
age = models.IntegerField(default=20)
phone = models.CharField(max_length=16)
addtime=models.DateTimeField(default=datetime.now)
def __str__(self):
return self.name+":"+self.phone
4.2 测试Model类的使用
在项目根目录下执行命令: python3 manage.py shell
[root@localhost myweb]# ls
myweb manage.py myapp
[root@localhost myweb]# python3 manage.py shell
Python 3.6.1 (default, Jul 18 2017, 01:35:19)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-18)] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from myapp.models import Users
>>> Users.objects.all()
<QuerySet [<Users: 张三:12345678901>, <Users: aa:13456789023>]>
>>> s = Users.objects.get(id=1)
>>> s.id
1
>>> s.name
'张三'
>>> s.age
20
>>> s.phone
'12345678901'
>>>
5. 实现Web端访问
5.1 编辑myweb/myweb/settings.py文件.做 ALLOWED_HOSTS 主机访问配置(若第三步已做可跳过此步骤)
#此处添加自己的IP地址
ALLOWED_HOSTS = ['localhost','127.0.0.1','172.16.142.129']
5.2 编写项目主路由urls配置,配置对myapp应用路由的访问连接配置
from django.conf.urls import include,url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('myapp.urls')),
]
5.3 配置当前应用myapp的路由配置
在myapp应用目录下创建一个路由文件urls.py文件,注意此文件编码为utf-8(建议复制一个)。
编辑应用中的路由配置文件:myweb/myapp/urls.py, 内容如下:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name="index"),
]
5.4 编辑视图文件:myweb/myapp/views.py,内容如下
#from django.shortcuts import render
from django.http import HttpResponse
from myapp.models import Users
def index(request):
try:
s = Users.objects.get(id=1)
return HttpResponse(s)
except:
return HttpResponse("没有找到对应的信息!")
5.5 测试
项目根目录下运行 python3 manage.py sunserver 0:8000
命令,开启服务:
[root@localhost myweb]# python3.6 manage.py runserver 0:8000
Performing system checks...
System check identified no issues (0 silenced).
July 28, 2017 - 14:01:52
Django version 1.11, using settings 'myweb.settings'
Starting development server at http://0:8000/
Quit the server with CONTROL-C.
打开浏览器,在浏览其中输入网址测试:http://172.16.142.129:8000
显示结果:张三:12345678901
继续上面操作完成Web版的Users信息增 删 改 查
1. 准备模板文件,创建模板目录
- 在项目目录下创建templates模板目录
- 进入模板目录templates,在模板目录下创建应用名myapp的目录
- 进入myapp目录,在里面创建一个users目录
- 进入users目录,在里面创建文件:index.html,add.html,edit.html,menu.html,info.html
5 设置模板目录信息:编辑myweb/myweb/settings.py文件(若第三步已做可跳过此步骤)
...
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates'),],
'APP_DIRS': True,
...
2. 配置路由信息
打开文件:myweb/myapp/urls.py路由文件,加入六条路由配置信息
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name="index"),
url(r'^users$', views.indexUsers, name="users"), #浏览用户信息
url(r'^users/add$', views.addUsers, name="addusers"), #加载添加用户信息表单
url(r'^users/insert$', views.insertUsers, name="insertusers"), #执行用户信息添加
url(r'^users/(?P<uid>[0-9]+)/del$', views.delUsers, name="delusers"), #执行用户信息删除
url(r'^users/(?P<uid>[0-9]+)/edit$', views.editUsers, name="editusers"), #加载用户信息编辑表单
url(r'^users/update$', views.updateUsers, name="updateusers"), #执行用户信息编辑
]
3. 编写视图文件:myweb/myapp/views.py
# 注意:需导入from django.shortcuts import render
from django.shortcuts import render
from django.http import HttpResponse
from myapp.models import Users
def index(request):
try:
list = Users.objects.filter(id__in=[1,3,5])
s = ','.join([vo.name for vo in list])
#修改(将id值为5的age值改为30)
#ob = Users.objects.get(id=5)
#ob.age = 30
#ob.save()
#删除(删除id为3的信息)
#ob = Users.objects.get(id=3)
#ob.delete()
return HttpResponse(s)
except:
return HttpResponse("没有找到对应的信息!")
# 浏览用户信息
def indexUsers(request):
# 执行数据查询,并放置到模板中
list = Users.objects.all()
context = {"stulist":list}
return render(request,"myapp/users/index.html",context)
# 加载添加信息表单
def addUsers(request):
return render(request,"myapp/users/add.html")
# 执行信息添加操作
def insertUsers(request):
try:
ob = Users()
ob.name = request.POST['name']
ob.age = request.POST['age']
ob.phone = request.POST['phone']
ob.save()
context = {'info':'添加成功!'}
except:
context = {'info':'添加失败!'}
return render(request,"myapp/users/info.html",context)
# 执行信息删除操作
def delUsers(request,uid):
try:
ob = Users.objects.get(id=uid)
ob.delete()
context = {'info':'删除成功!'}
except:
context = {'info':'删除失败!'}
return render(request,"myapp/users/info.html",context)
# 加载信息编辑表单
def editUsers(request,uid):
try:
ob = Users.objects.get(id=uid)
context = {'user':ob}
return render(request,"myapp/users/edit.html",context)
except:
context = {'info':'没有找到要修改的信息!'}
return render(request,"myapp/users/info.html",context)
# 执行信息编辑操作
def updateUsers(request):
try:
ob = Users.objects.get(id= request.POST['id'])
ob.name = request.POST['name']
ob.age = request.POST['age']
ob.phone = request.POST['phone']
#ob.addtime = datetime.now
ob.save()
context = {'info':'修改成功!'}
except:
context = {'info':'修改失败!'}
return render(request,"myapp/users/info.html",context)
4. 编辑浏览信息视图文件:
文件位置:myweb/templates/myapp/users/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>用户信息管理</title>
<script>
//自定义执行信息删除提示判断,参数uu是成功的删除url地址
function doDel(uu){
if(confirm("确定要删除吗?")){
//网页跳转
window.location=uu;
}
}
</script>
</head>
<body>
<center>
{% include 'myapp/users/menu.html' %}
<h3>浏览用户信息</h3>
<table width="800" border="1">
<tr>
<th>id号</th>
<th>姓名</th>
<th>年龄</th>
<th>电话</th>
<th>添加时间</th>
<th>操作</th>
</tr>
{% for stu in stulist %}
<tr>
<td>{{ stu.id }}</td>
<td>{{ stu.name }}</td>
<td>{{ stu.age }}</td>
<td>{{ stu.phone }}</td>
<td>{{ stu.addtime|date:'Y-m-d H:i:s' }}</td>
<td>
<a href="{% url 'editusers' stu.id %}">编辑</a>
<a href="javascript:doDel('{% url 'delusers' stu.id %}');">删除</a>
</td>
</tr>
{% endfor %}
</table>
</center>
</body>
</html>
5. 编辑添加表单视图文件
文件位置:myweb/templates/myapp/users/add.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>用户信息管理</title>
</head>
<body>
<center>
{% include "myapp/users/menu.html" %}
<h3>添加用户信息</h3>
<form action="{% url 'insertusers' %}" method="post">
{% csrf_token %}
<table width="280" border="0">
<tr>
<td>姓名:</td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td>年龄:</td>
<td><input type="text" name="age"/></td>
</tr>
<tr>
<td>电话:</td>
<td><input type="text" name="phone"/></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="添加"/>
<input type="reset" value="重置"/>
</td>
</tr>
</table>
</form>
</center>
</body>
</html>
6. 编辑信息表单视图文件
文件位置:myweb/templates/myapp/users/edit.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>用户信息管理</title>
</head>
<body>
<center>
{% include "myapp/users/menu.html" %}
<h3>修改用户信息</h3>
<form action="{% url 'updateusers' %}" method="post">
<input type="hidden" name="id" value="{{ user.id}}"/>
{% csrf_token %}
<table width="280" border="0">
<tr>
<td>姓名:</td>
<td><input type="text" name="name" value="{{ user.name }}"/></td>
</tr>
<tr>
<td>年龄:</td>
<td><input type="text" name="age" value="{{ user.age }}"/></td>
</tr>
<tr>
<td>电话:</td>
<td><input type="text" name="phone" value="{{ user.phone }}"/></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="编辑"/>
<input type="reset" value="重置"/>
</td>
</tr>
</table>
</form>
</center>
</body>
</html>
7. 编辑公共导航栏页视图文件
文件位置:myweb/templates/myapp/users/menu.html
<h2>用户信息管理</h2>
<a href="{% url 'users' %}">浏览用户</a> |
<a href="{% url 'addusers' %}">添加用户</a>
<hr/>
文件位置:myweb/templates/myapp/users/info.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>用户信息管理</title>
</head>
<body>
<center>
{% include "myapp/users/menu.html" %}
<h3>{{ info }}</h3>
</center>
</body>
</html>