Python 使用 Django 框架,进行 web 开发,一点都不比目前 JavaEE 最简便的框架 SpringBoot 差,甚至是更加便捷。
① 使用 python manage.py makemigrations
、python manage.py migrate
,即可实现 JavaEE 方面的 JPA框架 的代码操作数据库的功能
② 使用例如 python manage.py inspectdb > booktest/models.py
(booktest/models.py 为自己的模型代码位置),即可实现 类似 MyBatis 的逆向工程,通过数据库中建立的表自动生成相应的 model 代码
③ 模型.objects
下已经实现了基本 CRUD 的方法,可以直接调用,类似 SpringBoot 中的 SpringData+JPA
的功能,且代码量极少。
④ ….等等
本文代码改自前文:[增删改查] 使用 React 做后台管理 CRUD 界面和 RESTful 交互
只不过交互从 React 改为强大的Django模板引擎
下面来个案例,使用 Python 做小型项目须知
2018.7.14 更新,代码已经放在 github 上:https://github.com/larger5/Django_CRUD_Student.git
M+V+T+url+settings
from django.db import models
class student_info(models.Model):
# 字符
t_name=models.CharField(max_length=20,default='linhongcun')
# 数字
t_age=models.IntegerField(default=21) # 使用数字长度设置无效
# 图片
t_image=models.CharField(max_length=300,default='http://itaem.oss-cn-shenzhen.aliyuncs.com/20180509083509.jpg?Expires=4679469344&OSSAccessKeyId=LTAIATBJKsu6vu4R&Signature=PJkwOp9DVhtYu3Xkka0MnZVfnP0%3D')
from django.shortcuts import render,redirect
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings # 获取 settings.py 里边配置的信息
import os
from .models import *
# 1.1.前往 index 页(all)
def all_page(request):
data = student_info.objects.all()
content={'data': data}
return render(request, 'student/all.html', content)
# 1.2.前往 add 页
def add_page( request ):
return render(request, 'student/add.html')
# 2.增
@csrf_exempt
def add_student(request):
t_name = request.POST['tName']
t_age = request.POST['tAge']
t_image = request.FILES['tImage']
fname = os.path.join(settings.MEDIA_ROOT, t_image.name)
with open(fname, 'wb') as pic:
for c in t_image.chunks():
pic.write(c)
student=student_info()
student.t_name=t_name
student.t_age=t_age
# 存访问路径到数据库
student.t_image = os.path.join("/static/media/", t_image.name)
student.save()
return redirect('/allPage')
# 3.1.查 - name
def search_student(request):
t_name = request.GET['q']
student=student_info.objects.filter(t_name=t_name)
content={'data':student}
return render(request,'student/all.html', content)
# 3.2.查 - id
def search_student_id(request,student_id):
student=student_info.objects.filter(id=student_id)
content = {'data': student}
print(content)
return render(request,'student/update.html',content)
# 4.改
@csrf_exempt
def update_student(request):
id=request.POST['t_id']
t_name = request.POST['tName']
t_age = request.POST['tAge']
# 缺陷:文件必传
t_image = request.FILES['tImage']
fname = os.path.join(settings.MEDIA_ROOT, t_image.name)
with open(fname, 'wb') as pic:
for c in t_image.chunks():
pic.write(c)
t_image = os.path.join("/static/media/", t_image.name)
student_info.objects.filter(id=id).update(t_name=t_name,t_age=t_age,t_image=t_image)
return redirect('/allPage')
# 5.删
def delete_student(request,student_id):
student_info.objects.filter(id=student_id).delete()
return redirect('/allPage')
<html lang="en">
<head>
<meta charset="UTF-8">
<title>DjangoCURDtitle>
{# 注意引入文件的方式 #}
{% load staticfiles %}
<link rel="stylesheet" href="/static/layui/css/layui.css">
{# 设置网页标题图标 #}
<link rel="icon" type="image/x-icon" href="/static/media/icon.ico" />
head>
<body>
{% block content %}
{% endblock %}
body>
html>
{% extends "student/base.html" %}
{% block content %}
<div class="layui-container">
<blockquote class="layui-elem-quote">
<h1>CRUD——Django + LayUIh1>
blockquote>
{# 查询学生模块 #}
<form action="/search" method="get">
<input placeholder="学生名" name="q" id="q">
<input type="submit" class="layui-btn" value="搜索">
form>
{# 显示所有学生模块 #}
<table class="layui-table">
<colgroup>
<col width="150">
<col width="200">
<col>
colgroup>
<thead>
<tr>
<th>idth>
<th>姓名th>
<th>年龄th>
<th>图片th>
<th>修改th>
<th>删除th>
tr>
thead>
<tbody>
{%for student in data%}
<tr>
<td>{{student.id}}td>
<td>{{student.t_name}}td>
<td>{{student.t_age}}td>
<td>
<img src="{{ student.t_image }}" height="50px">
td>
<td>
{# 修改学生模块 #}
<a href="/get/{{ student.id }}" class="layui-btn layui-btn-normal">
<i class="layui-icon">i>修改
a>
td>
<td>
{# 删除学生模块 #}
<a href="/delete/{{ student.id }}" class="layui-btn layui-btn-danger">
<i class="layui-icon">i>删除
a>
td>
tr>
{%endfor%}
tbody>
table>
{# 添加学生模块 #}
<a href="/addPage" class="layui-btn layui-btn-warm">
<i class="layui-icon">i> 添加
a>
div>
{% endblock %}
{% extends "student/base.html" %}
{% block content %}
<div class="layui-container">
<blockquote class="layui-elem-quote">
<h1>Add Studenth1>
blockquote>
<div class="layui-row">
<div class="layui-col-md5">
<form action="/addStudent/" method="post" enctype="multipart/form-data"/>
<hr class="layui-bg-green">
<input type="text" name="tName" id="tName" placeholder="学生名" class="layui-input"/>
<hr class="layui-bg-green">
<input type="text" name="tAge" id="tAge" placeholder="学生年龄" class="layui-input"/>
<hr class="layui-bg-green">
<input type="file" name="tImage" id="tImage"/>
<hr class="layui-bg-green">
<input type="submit" value="添加" class="layui-btn"/>
form>
div>
div>
div>
{% endblock %}
{% extends "student/base.html" %}
{% block content %}
<div class="layui-container">
<blockquote class="layui-elem-quote">
<h1>Update Student Pageh1>
blockquote>
<div class="layui-row">
{%for student in data%}
<div class="layui-col-md5">
<form action="/updateStudent/" method="post" enctype="multipart/form-data"/>
<input type="text" name="t_id" id="t_id" placeholder="id" class="layui-input" value="{{ student.id}}" />
<hr class="layui-bg-green">
<input type="text" name="tName" id="tName" placeholder="学生名" class="layui-input" value="{{ student.t_name}}"/>
<hr class="layui-bg-green">
<input type="text" name="tAge" id="tAge" placeholder="学生年龄" class="layui-input" value="{{ student.t_age }}"/>
<hr class="layui-bg-green">
<input type="file" name="tImage" id="tImage"/>
<hr class="layui-bg-green">
<img src="{{ student.t_image }}" height="50px">
<hr class="layui-bg-green">
<input type="submit" value="修改" class="layui-btn"/>
form>
div>
div>
{% endfor %}
div>
{% endblock %}
from django.contrib import admin
from django.urls import path
# 注意要引入 url
from django.conf.urls import url
# 注意要引入自己的 views
from student import views
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^allPage/$', views.all_page), # 前往所有学生的网页
url(r'^addPage/$', views.add_page), # 前往新增学生的网页
url(r'^addStudent/$', views.add_student), # 添加学生的 dao 操作
url(r'^search/$', views.search_student), # 根据 t_name 查找学生的 dao 操作
url(r'^get/(?P[0-9]*)/$' , views.search_student_id), # 根据 id 查找学生的 dao 操作
url(r'^updateStudent/$', views.update_student), # 修改学生的 dao 操作
url(r'^delete/(?P[0-9]*)/$' , views.delete_student), # 删除学生的 dao 操作
]
5.1.参考资料
《精通 Django》 Nigel George 著
5.2.其他
解决pip install 速度慢、pycharm激活的问题
5.3.问题与解决
Django 中bootstrap的引用
六.Django中URL的参数传递