数据库设计(models.py)
class Music(models.Model):
""" 音乐 """
name = models.CharField(verbose_name="音乐名字", max_length=32)
singer = models.CharField(verbose_name="歌手", max_length=32)
# 本质上数据库也是CharField,自动保存数据。
music = models.FileField(verbose_name="音频", max_length=128)
链接(urls.py)
# 音频上传
path('music/upload/', music.music_upload),
path('music/add/', music.music_add),
处理代码(music.py)
from django.shortcuts import render, redirect
from app01 import models
def music_upload(request):
queryset = models.Music.objects.all()
return render(request, 'music_upload.html', {'queryset': queryset})
from app01.utils.bootstrap import BootStrapModelForm
class UpModelForm(BootStrapModelForm):
bootstrap_exclude_fields = ['music']
class Meta:
model = models.Music
fields = "__all__"
def music_add(request):
""" 上传文件和数据 """
title = "音频上传"
if request.method == "GET":
form = UpModelForm()
return render(request, 'upload_form.html', {"form": form, "title": title})
form = UpModelForm(data=request.POST, files=request.FILES)
if form.is_valid():
# 对于文件:自动保存;
# 字段 + 上传路径写入到数据库
form.save()
return redirect("/music/upload/")
return render(request, 'upload_form.html', {"form": form, "title": title})
前端页面(music_upload.html)
{% extends 'layout.html' %}
{% block content %}
<div class="container">
<div style="margin-bottom: 10px">
<a class="btn btn-success" href="/music/add/" target="_blank">
<span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>
音频上传
</a>
</div>
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading">
<span class="glyphicon glyphicon-th-list" aria-hidden="true"></span>
音频列表
</div>
<!-- Table -->
<table class="table table-bordered">
<thead>
<tr>
<th>音频</th>
<th>音乐名称</th>
<th>歌手</th>
</tr>
</thead>
<tbody>
{% for obj in queryset %}
{% if obj.music.name|slice:'-4:' == ".mp3" %}
<tr>
<td>
{% if obj.music.name|slice:'-4:' == ".png" %}
<img src="/media/{{ obj.music }}" style="height: 80px;">
{% else %}
<audio controls>
<source src="/media/{{ obj.music }}">
</audio>
{% endif %}
</td>
<td>{{ obj.name }}</td>
<td>{{ obj.singer }}</td>
</tr>
{% endif %}
{% endfor %}
</tbody>
</table>
</div>
<div class="clearfix">
<ul class="pagination" style="float:left;">
{{ page_string }}
</ul>
</div>
</div>
{% endblock %}
前端页面(upload_form.html)
{% extends 'layout.html' %}
{% block content %}
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">{{ title }}</h3>
</div>
<div class="panel-body">
<form method="post" enctype="multipart/form-data" novalidate>
{% csrf_token %}
{% for field in form %}
<div class="form-group">
<label>{{ field.label }}</label>
{{ field }}
<span style="color: red;">{{ field.errors.0 }}</span>
</div>
{% endfor %}
<button type="submit" class="btn btn-primary">提 交</button>
</form>
</div>
</div>
</div>
{% endblock %}
页面展示