是否要安装pycharm?
有vscode就可以了,另外vscode不吃cpu,我基本上开发都上vscode上。
1.创建工程,如djtest,然后用vscode打开
2.用venv创建python虚拟环境
python -m venv {虚拟环境名称}
python -m venv venv1
3.运行虚拟环境
{虚拟环境名称}\Scripts\activate
退出虚拟环境:
deactivate
可能会出现报错:vscode运行python时提示无法加载文件xxx.venv\Scripts\activate.ps1
参考文章:解决vscode运行python时,提示无法加载文件xxx.venv\Scripts\activate.ps1,未对文件进行数字签名,因为在此系统上禁止运行脚本。
4.安装django
pip install django
5.创建django工程
django-admin startproject {工程名称}
django-admin startproject djtest
6.运行工程
python manage.py runserver
参考文章:vscode 搭建 django 显示hello world
基于上一目录的demo进一步开发,文件的功能,和弄清路由怎么实现
应用为testapp
cmd转到第一层的djtest文件夹。
python manage.py startapp testapp
将此应用添加到setting.py
djtest: 项目的容器。
djtest/settings.py: 该 Django 项目的设置/配置文件。
INSTALLED_APPS = [
'testapp',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
在djtest目录下的urls.py添加应用的URL
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('testapp/',include('testapp.urls')),
]
设置url:在testapp目录下新建urls.py
from django.urls import path
from . import views
app_name = 'testapp'
urlpatterns = [
path('',views.index,name='index'),
]
打开testapp目录下的views.py,写入
from django.shortcuts import render
# Create your views here.
def index(myrequest):
pamdict = {'name':'老铁'}
return render(myrequest,'testapp/myindex.html',pamdict)
在testapp目录下新建templates文件夹,在templates下再新建testapp文件夹,在此testapp目录下新建myindex.html
<!DOCTYPE html>
<html>
<head>
<title>首页</title>
</head>
<body>
<h1>欢迎>>>{{name}}<<<到访</h1>
</body>
</html>
基于上两层目录创建django工程djtest1,和应用stu
在本地MySQL创建djtest1数据库,修改项目的settings连接信息由默认的sqlite修改为MySQL
create databases djtest1;
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'djtest1',
'USER': 'root',
'PASSWORD': '154524',
'HOST': '127.0.0.1',
'PORT': 3306
}
}
参考文章:vscode连接本地创建的数据库
可以连接自己创建的数据库
在应用stuapp下models.py添加Student模型
class Student(models.Model):
student_no = models.CharField(max_length=32, unique=True)
student_name = models.CharField(max_length=32)
Terminal终端输入以下两条命令,其作用第一条生成文件记录模型的变化;第二条是将模型变化同步至数据库,我们可以在数据库生成对应的表结构。
python manage.py makemigrations stuapp
python manage.py migrate stuapp
例如时区问题,ValueError: Problem installing fixture ‘D:\software\python\prj\test5\xxxops\server\db.json’: Could not load system.Permission(pk=1): MySQL backend does not support timezone-aware datetimes when USE_TZ is False.
办法总比困难多,多思考,不怕南
Json–>转sql
传送门:http://tool.p2hp.com/tool-format-json/
然后在Mysql里面执行sql就OK了
本质可以理解请求路径url和处理方法的映射配置,首先在项目djtest1的urls.py文件中添加stuapp的路由配置。
path('stu/', include('stuapp.urls')),
然后在stuapp添加一个名为urls.py的文件,添加路由配置如下
# coding=utf-8
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index),
url(r'^add/$', views.add),
url(r'^edit/$', views.edit),
url(r'^delete/$', views.delete)
]
在应用stuapp的视图层文件views.py添加对应学生信息增删改查的处理函数,这里我使用的原生SQL,便于深入理解其执行过程。后面有时间我会在github上添加Django框架提供的操作数据库方式。
import MySQLdb
from django.shortcuts import render, redirect
# Create your views here.
# 学生信息列表处理函数
def index(request):
conn = MySQLdb.connect(host="localhost", user="root", passwd="154524", db="djtest1", charset='utf8')
with conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) as cursor:
cursor.execute("SELECT id,student_no,student_name FROM stuapp_student")
students = cursor.fetchall()
return render(request, 'stu/index.html', {'students': students})
# 学生信息新增处理函数
def add(request):
if request.method == 'GET':
return render(request, 'stu/add.html')
else:
student_no = request.POST.get('student_no', '')
student_name = request.POST.get('student_name', '')
conn = MySQLdb.connect(host="localhost", user="root", passwd="154524", db="djtest1", charset='utf8')
with conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) as cursor:
cursor.execute("INSERT INTO stuapp_student (student_no,student_name) "
"values (%s,%s)", [student_no, student_name])
conn.commit()
return redirect('../')
# 学生信息修改处理函数
def edit(request):
if request.method == 'GET':
id = request.GET.get("id")
conn = MySQLdb.connect(host="localhost", user="root", passwd="154524", db="djtest1", charset='utf8')
with conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) as cursor:
cursor.execute("SELECT id,student_no,student_name FROM stuapp_student where id =%s", [id])
student = cursor.fetchone()
return render(request, 'stu/edit.html', {'student': student})
else:
id = request.POST.get("id")
student_no = request.POST.get('student_no', '')
student_name = request.POST.get('student_name', '')
conn = MySQLdb.connect(host="localhost", user="root", passwd="154524", db="djtest1", charset='utf8')
with conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) as cursor:
cursor.execute("UPDATE stuapp_student set student_no=%s,student_name=%s where id =%s",
[student_no, student_name, id])
conn.commit()
return redirect('../')
# 学生信息删除处理函数
def delete(request):
id = request.GET.get("id")
conn = MySQLdb.connect(host="localhost", user="root", passwd="154524", db="djtest1", charset='utf8')
with conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) as cursor:
cursor.execute("DELETE FROM stuapp_student WHERE id =%s", [id])
conn.commit()
return redirect('../')
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>学生列表</title>
</head>
<body>
<table border="1px" width="100%" style="border-collapse: collapse;">
<a href="../stu/add/">添加学生</a>
<tr>
<th>编号</th>
<th>姓名</th>
<th>学号</th>
<th>操作</th>
</tr>
{% for student in students %}
<tr>
<td align="center">{{ forloop.counter }} </td>
<td align="center">{{ student.student_name }} </td>
<td align="center">{{ student.student_no }} </td>
<td align="center">
<a href="../stu/edit/?id={{ student.id }}">
编辑
</a>
<a href="../stu/delete/?id={{ student.id }}">
删除
</a>
</td>
</tr>
{% endfor %}
</table>
</body>
</html>
学生信息新增页
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>学生添加</title>
<style>
form {
margin: 20px auto;
width: 500px;
border: 1px solid #ccc;
padding: 20px
}
</style>
</head>
<body>
<form method="post" action="../add/">
{% csrf_token %}
<table>
<tr>
<th>姓名</th>
<td><input name="student_name"></td>
</tr>
<tr>
<th>学号</th>
<td><input name="student_no"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit"/>
</td>
</tr>
</table>
</form>
</body>
</html>
学生信息编辑页
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>学生编辑</title>
<style>
form {
margin: 20px auto;
width: 500px;
border: 1px solid #ccc;
padding: 20px
}
</style>
</head>
<body>
<form method="post" action="../edit/">
{% csrf_token %}
<input type="hidden" name="id" value="{{ student.id }}"/>
<table>
<tr>
<th>姓名</th>
<td><input name="student_name" value="{{ student.student_name }}"></td>
</tr>
<tr>
<th>学号</th>
<td><input name="student_no" value="{{ student.student_no }}"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit"/>
</td>
</tr>
</table>
</form>
</body>
</html>
参考文章:Python Web实战:Python+Django+MySQL实现基于Web版的增删改查
Django进阶Model篇—数据库操作(ORM)