Django中上传文件方式。
如何实现文件上传功能?
1创建项目uploadfile:
创建app: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,HttpResponsefrom django.views.generic import Viewfrom .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 pathfrom front import viewsfrom django.conf.urls.static import staticfrom django.conf import settingsurlpatterns = [ 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)可以直接访问文件。非常方便。
到此这篇关于Django中文件上传和文件访问微项目的方法的文章就介绍到这了,更多相关django上传文件和文件访问微项目内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!