杰网资源 Design By www.escxy.com
Django中上传文件方式。
如何实现文件上传功能?
1创建项目uploadfile:
创建app:front
项目设置INSTALLED_APPS中添加'front'
INSTALLED_APPS = [ ''' 'front' ]
#后面添加MEDIA_ROOT和MEDIA_URL
STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,'static') MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/'
2.models,views都写用front文件夹里面。
modes.py创建代码。
class Article(models.Model): '''创建个文章表格,测试上传文件''' title = models.CharField(max_length=100,unique=True) content = models.CharField(max_length=100) articlefile = models.FileField(upload_to='%Y/%m/%d',unique=True) #这里upload_to='%Y/%m/%d'可以先不设置,设置的目的是上传文件保存在media目录下时,自动创建以时间为标记文件层次文件夹目录
使用命令
makemigrations,和migrates进行迁移
打开db.sqlite3可以看到迁移成功后的数据表front_article
数据库中有article表,说明迁移成功。
3.写视图
from django.shortcuts import render,HttpResponse
from django.views.generic import View
from .models import Article
# Create your views here.
class UploadFile(View):
def get(self,request):
contents = Article.objects.all()
return render(request,'index.html',locals())
def post(self,request):
title = request.POST.get('title')
content = request.POST.get('content')
file = request.FILES.get('myfile')
Article.objects.create(title=title,content=content,articlefile=file)
return HttpResponse("成功")
这里使用类视图
4创建index模板。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% for content in contents %}
<li>标题:{{ content.title }}</li>
<li>内容:{{ content.content }}</li>
<a href="{% url 'index' %}media/{{ content.articlefile }}" rel="external nofollow" ><li>{{ content.articlefile }}</li></a>
{% endfor %}
{#for循环主要显示数据图中数据。有标题,有内容和文件链接#}
<form action="" method="post" enctype="multipart/form-data" >
<input type="text" name="title" >
<input type="text" name="content">
<input type="file" name="myfile" >
<input type="submit" value="提交">
</form>
</body>
</html>
显示效果如下:
5关键性一步
urls.py
from django.urls import path
from front import views
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('',views.UploadFile.as_view(),name='index'),
]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
使用static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)可以直接访问文件。非常方便。
杰网资源 Design By www.escxy.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
杰网资源 Design By www.escxy.com
暂无评论...
P70系列延期,华为新旗舰将在下月发布
3月20日消息,近期博主@数码闲聊站 透露,原定三月份发布的华为新旗舰P70系列延期发布,预计4月份上市。
而博主@定焦数码 爆料,华为的P70系列在定位上已经超过了Mate60,成为了重要的旗舰系列之一。它肩负着重返影像领域顶尖的使命。那么这次P70会带来哪些令人惊艳的创新呢?
根据目前爆料的消息来看,华为P70系列将推出三个版本,其中P70和P70 Pro采用了三角形的摄像头模组设计,而P70 Art则采用了与上一代P60 Art相似的不规则形状设计。这样的外观是否好看见仁见智,但辨识度绝对拉满。






