通过pycharm创建venv环境,目录为D:\project\djangoadmin(直接新建Django项目无法指定版本,默认下载最新版本,我这里想要安装2.1版本)
成功后进入终端Terminal自动进入venv根目录,指定源安装包
pip install django==2.2 -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install djangorestframework -i https://pypi.tuna.tsinghua.edu.cn/simple
pip list查看安装成功
将venv虚拟环境的python运行环境加入PATH系统环境变量,目录如下
D:\project\djangoadmin\venv\Scripts
创建mysite项目
cd venv\Scripts
django-admin.exe startproject mysite
进入目录启动项目,访问127.0.0.1:8080即可
python manage.py runserver 0.0.0.0:8000
目录结构说明
mysite
- mysite # 对整个程序进行配置
- init #一个空文件,它告诉Python这个目录应该被看做一个Python包
- settings # 项目配置文件
- url # URL对应关系(路由)
- wsgi # 遵循WSIG规范,uwsgi + nginx
- manage.py # 一个命令行工具,可以使你用多种方式对Django项目进行交互
dingding #应用目录
│ admin.py #对应应用后台管理配置文件。
│ apps.py #对应应用的配置文件。
│ models.py #数据模块,数据库设计就在此文件中设计
│ tests.py #自动化测试模块,可在里面编写测试脚本自动化测试
│ views.py #视图文件,用来执行响应代码的。你在浏览器所见所得都是它处理的。
│ __init__.py
│
├─migrations #数据迁移、移植文目录,记录数据库操作记录,内容自动生成。
│ │ __init__.py
pip install pymysql -i https://pypi.tuna.tsinghua.edu.cn/simple
############修改成mysql如下
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'test', #你的数据库名称
'USER': 'root', #你的数据库用户名
'PASSWORD': '123456', #你的数据库密码
'HOST': 'localhost', #你的数据库主机,留空默认为localhost
'PORT': '3306', #你的数据库端口
}}
import pymysql
pymysql.install_as_MySQLdb()
CREATE DATABASE `test` CHARACTER SET utf8 COLLATE utf8_general_ci;
class Music(models.Model):
music_author = models.CharField(max_length=50, verbose_name='歌唱者')
music_name = models.CharField(max_length=100, verbose_name='歌曲名')
music_album = models.CharField(max_length=100, verbose_name='专辑')
music_time = models.CharField(max_length=10, verbose_name='歌曲时间')
music_type = models.CharField(
max_length=100, null=True, verbose_name='歌曲类型', default=None)
music_lyrics = models.CharField(
max_length=100, blank=True, verbose_name='作词者')
music_arranger = models.CharField(
max_length=100, blank=True, verbose_name='作曲者')
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
from django.contrib import admin
from .models import Music
# Register your models here.
admin.site.register(Music)
from rest_framework import serializers
from dingding.models import *
class MusicSerializer(serializers.ModelSerializer):
class Meta:
fields = '__all__'
model = Music
3.2在mysite/urls.py里添加全局url,include应用dingding下的子url配置
from django.contrib import admin
from django.urls import path, include
from dingding import views
urlpatterns = [
path('admin/', admin.site.urls),
path('index', views.hello),
path('api/', include('dingding.urls')),
]
3.3在dingding/urls.py添加app应用url
from django.urls import path
from dingding.views import *
urlpatterns = [
path('', MusicList.as_view()),
path('/' , MusicDetailView.as_view()),
]
3.4添加views视图函数
dingding/views.py
from django.shortcuts import render
from django.http import HttpResponse
from rest_framework import generics
from rest_framework.views import APIView
from rest_framework.response import Response
from dingding.models import *
from dingding.serializers import MusicSerializer
# Create your views here.
def hello(request):
return HttpResponse('hello world')
class MusicList(APIView):
def get(self, request):
queryset = Music.objects.all()
ret = MusicSerializer(queryset, many=True)
return Response(ret.data)
def post(self, request):
music = MusicSerializer(data=request.data)
print(request.data)
if music.is_valid():
music.save()
return Response(music.data)
else:
return Response(music.errors)
class MusicDetailView(APIView):
def get(self, request, pk):
music = Music.objects.filter(pk=pk).first()
music_ser = MusicSerializer(music)
return Response(music_ser.data)
def put(self, request, pk):
music = Music.objects.filter(pk=pk).first()
music_ser = MusicSerializer(music, data=request.data)
if music_ser.is_valid():
music_ser.save()
return Response(music_ser.data)
else:
return Response(music_ser.errors)
# 根据id删除
def delete(self, request, pk):
Music.objects.filter(pk=pk).delete()
return Response()
INSERT INTO `test`.`dingding_music` (`music_author`, `music_name`, `music_album`, `music_time`, `music_type`, `music_lyrics`, `music_arranger`) VALUES ('张学友', '爱如潮水', '吻别', '1997年1月', '流行', '张学友', '张学友');