项目准备
- 创建一个项目和一个子应用
- 创建一个apps文件夹存放子应用,并将apps设置为源根。
settings.py中的配置
-
配置apps文件夹的路径 -
settings.py 中添加子应用 -
注释MIDDLEWARE中的 ‘django.middleware.csrf.CsrfViewMiddleware’ -
在settings.py中设置好数据库和media静态文件的设置
主路由urls.py的配置
子应用中的文件代码
_init_.py
from pymysql import install_as_MySQLdb
install_as_MySQLdb()
admin.py
from django.contrib import admin
from drfapp.models import SimdFiles
@admin.register(SimdFiles)
class SimdFiles_admin(admin.ModelAdmin):
list_display = ['title', 'file', 'add_time']
models.py
from django.db import models
from datetime import datetime
class SimdFiles(models.Model):
title = models.CharField(max_length=200, verbose_name='文件名称')
file = models.FileField(upload_to='file_url', verbose_name='文件路径')
add_time = models.DateTimeField(default=datetime.now(), verbose_name='文件添加时间')
class Meta:
db_table = 'SimdFiles'
verbose_name = '上传文件'
verbose_name_plural = verbose_name
serializers.py
from rest_framework import serializers
from drfapp.models import SimdFiles
class SimdFilesSerializer(serializers.ModelSerializer):
class Meta:
model = SimdFiles
fields = ['title', 'file', 'add_time']
urls.py
from django.urls import re_path
from drfapp.views import SimdFielsViews
urlpatterns = [
re_path(r'^file/$', SimdFielsViews.as_view({'get':'list'})),
]
views.py
from drfapp.models import SimdFiles
from drfapp.serializers import SimdFilesSerializer
from rest_framework import viewsets
from rest_framework.response import Response
class SimdFielsViews(viewsets.ModelViewSet):
serializer_class = SimdFilesSerializer
def get_queryset(self):
return SimdFiles.objects.all()
演示
在admin中上传文件
rest_framework中下载
- 重新输入路由路径
回车后即可看到rest_framework界面
- 点击文件路由即可下载
|