Django中文件上傳和文件訪問微項目的方法
Django中上傳文件方式。
如何實現(xiàn)文件上傳功能?
1創(chuàng)建項目uploadfile:

創(chuàng)建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創(chuàng)建代碼。
class Article(models.Model): '''創(chuàng)建個文章表格,測試上傳文件''' 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目錄下時,自動創(chuàng)建以時間為標記文件層次文件夾目錄
使用命令
makemigrations,和migrates進行遷移
打開db.sqlite3可以看到遷移成功后的數(shù)據(jù)表front_article

數(shù)據(jù)庫中有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創(chuàng)建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>內(nèi)容:{{ content.content }}</li>
<a href="{% url 'index' %}media/{{ content.articlefile }}" rel="external nofollow" ><li>{{ content.articlefile }}</li></a>
{% endfor %}
{#for循環(huán)主要顯示數(shù)據(jù)圖中數(shù)據(jù)。有標題,有內(nèi)容和文件鏈接#}
<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)可以直接訪問文件。非常方便。
到此這篇關于Django中文件上傳和文件訪問微項目的方法的文章就介紹到這了,更多相關django上傳文件和文件訪問微項目內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Mac中PyCharm配置Anaconda環(huán)境的方法
這篇文章主要介紹了Mac中PyCharm配置Anaconda環(huán)境的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-03-03
python開發(fā)中range()函數(shù)用法實例分析
這篇文章主要介紹了python開發(fā)中range()函數(shù)用法,以實例形式較為詳細的分析了Python中range()函數(shù)遍歷列表的相關技巧,需要的朋友可以參考下2015-11-11

