1.创建django项目并做好相关配置
首先在pycharm高级版中创建django项目
(1)选择左上角的四条小横线,然后找到文件下面的新建项目并点击,如下图:
(2)点击完上图的新建项目之后,来到下面的页面. 然后点击左上角的Django,然后设置文件的位置,之后将模版文件夹的template这个单词清空,最后在应用程序名称填上app,而后点击创建,django项目就创建完成了,剩下的就是在创建完成之后的一些配置了.
(3) 创建完成django之后,在app应用下一定要创建urls.py文件,用来写路由.
(4).在下面那个urls.py文件中写入如下代码:
"""login_hou URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('app/', include('app.urls')),
]
(5).之后要在settings.py文件中一般是第43行写上 'corsheaders' (如果你是社区版,你还需要另外写一行代码'app'),将50行 'django.middleware.csrf.CsrfViewMiddleware'注释掉(不注释的话,无法完成添加功能),在54行加上 'corsheaders.middleware.CorsMiddleware',在56行加上CORS_ORIGIN_ALLOW_ALL = True 这串代码,如下图所示 当然了,你在vscode中配置前后端连接的话就不用在后端配置第(4)步了
如果你在vscode中配置前后端连接,如下图,在 vue.config.js中如下配置:切记前后端口号要保持一致
(6). 配置数据库,将你提前创建好的数据库写到DATABASES中:
注意ENGING最后一个单词要改成mysql,NAME对应你数据库名字
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'login_di4zhou',
'PASSWORD': 'root',
'USER': 'root',
'HOST': '127.0.0.1',
}
}
(7).在app应用下找到models.py文件,写数据库所需字段,注意继承 Model:代码如下
from django.db import models
# Create your models here.
class Users(models.Model):
name = models.CharField(max_length=64)
pwd = models.IntegerField()
class People(models.Model):
img = models.CharField(max_length=64)
age = models.IntegerField(default=0)
name = models.CharField(max_length=64)
addr = models.CharField(max_length=64)
sex = models.CharField(max_length=64)
status = models.BooleanField(default=True)
isdel = models.IntegerField(default=1)
create_time = models.BigIntegerField(default=1715994190738)
上面我所写的代码, BigIntegerField 一般用来定义时间戳所用到,default是默认值
你所需要的字段全部定义完成之后需要先迁移表然后再生成表,代码依次在终端输入:
python manage.py makemigrations
python manage.py migrate
记得小皮一定要提前启动嗷
然后你就会发现你的navicat中出现了你所需要的那些字段
(8).在views.py中写你的后端接口,下面我将展示一下我自己写的增,删,改,查,搜索,分页,批量删除,登录,的接口:
import json
import time
from django.db.models import Q
from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from app.models import *
# Create your views here.
class UsersView(View):
# 登录
def post(self, request):
user_data = json.loads(request.body)
try:
user = Users.objects.get(name=user_data['name'], pwd=user_data['pwd'])
return JsonResponse({
'msg': '200',
'data': {'name': user.name, 'pwd': user.pwd}
})
except:
return JsonResponse({
'msg': '400',
})
# 修改数据
def put(self, request):
new_people = json.loads(request.body)
print(new_people)
People.objects.filter(id=new_people['id']).update(
name=new_people['name'],
addr=new_people['addr'],
sex=new_people['sex'],
status=new_people['status'],
age=new_people['age'],
img=new_people['img'],
create_time=new_people['create_time']
)
return JsonResponse({
'msg': '200'
})
class PeopleView(View):
# 数据渲染
def get(self, request):
isdel = int(request.GET.get('isdel', 1))
key = request.GET.get('key', '')
min = request.GET.get('min', '')
max = request.GET.get('max', '')
s_time = int(request.GET.get('s_time', 0))
e_time = int(request.GET.get('e_time', 0))
people = People.objects.all().filter(isdel=isdel)
# Q查询搜索
q = Q()
if key != '':
q.add(('name__contains', key), 'AND')
if min != '':
q.add(('age__gte', min), 'AND')
if max != '':
q.add(('age__lte', max), 'AND')
if s_time >0:
q.add(('create_time__gte', s_time), 'AND')
if e_time >0:
q.add(('create_time__lte', e_time), 'AND')
people = people.filter(q)
print(people)
# 分页
page = int(request.GET.get('page', 1))
pagesize = int(request.GET.get('pagesize', 2))
peoples = people.count()
start = (page - 1) * pagesize
end = page * pagesize
people = people[start:end]
people_list = []
for i in people:
people_list.append({
'id': i.id,
'name': i.name,
'addr': i.addr,
'sex': i.sex,
'status': i.status,
'age': i.age,
'img': i.img,
'create_time': i.create_time
})
return JsonResponse({
'data': people_list,
'peoples': peoples
})
# 添加数据
def post(self, request):
new_people = json.loads(request.body)
People.objects.create(
name=new_people['name'],
addr=new_people['addr'],
sex=new_people['sex'],
status=new_people['status'],
age=new_people['age'],
img=new_people['img'],
create_time=int(time.time() * 1000)
)
return JsonResponse({
'msg': '200'
})
# 状态修改
def put(self, request):
id = request.GET.get('id')
people = People.objects.get(id=id)
if people.status == True:
people.status = False
else:
people.status = True
people.save()
return JsonResponse({
'msg': '200'
})
# 单独删除/批量删除
def delete(self, request):
isdel = request.GET.get('isdel')
ids = request.GET.get('id')
id_list = ids.split(',')
for id in id_list:
people = People.objects.get(id=id)
people.isdel = isdel
people.save()
return JsonResponse({
'msg': '200'
})
(9).在app应用下面的urls.py文件中定义路由,如下:
from django.urls import path,include
from app.views import *
urlpatterns = [
path('UsersView/', UsersView.as_view()),
path('PeopleView/', PeopleView.as_view()),
]
补充:pycharm有一个简单的运行命令,就不必每次在终端输入命令了:
首先点击这个小三角,点击它下面的编辑配置:
然后勾选自定义运行命令并填上runserver,端口号设置成前后端一样的,点击确定即可.
然后后端每次运行点击这个小三角就可以了: