Django上传文件最简单最官方的方法
1.配置media路径
在settings.py中添加如下代码:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
2.定义数据表
import os
from django.db import models
from django.utils.timezone import now as timezone_now
def upload_to(instance, filename):
now = timezone_now()
base, ext = os.path.splitext(filename)
ext = ext.lower()
return f'quotes/{now:%Y/%m/%Y%m%d%H%M%S}{ext}'
class Quote(models.Model):
class Meta:
verbose_name = 'quote'
verbose_name_plural = verbose_name
author = models.CharField('author', max_length=200)
quote = models.TextField('quote')
picture = models.ImageField('picture', upload_to=upload_to, blank=True, null=True)
def __str__(self):
return self.quote
这里的upload_to函数会自动把文件的名称修改为日期型的名称,不会重名。
相关推荐:《Python视频教程》
3.添加form表单
forms.py文件
from django import forms
from .models import Quote
class QuoteForm(forms.ModelForm):
class Meta:
model = Quote
fields = '__all__'
4.编写视图代码
from django.shortcuts import render, redirect
from .forms import QuoteForm
def add_quote(request):
form = QuoteForm()
if request.method == 'POST':
form = QuoteForm(
data=request.POST,
files=request.FILES
)
if form.is_valid():
form.save()
return redirect('quote:add_quote')
else:
return render(request, 'quotes/add_quote.html', {
'form': form
})
5.编写模板html代码
<form action="{% url 'quote:add_quote' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">save</button>
</form>
6.添加url映射
在app的目录的urls.py添加
from django.urls import path
from quotes.views import add_quote
app_name = 'quote'
urlpatterns = [
path('add/', add_quote, name='add_quote')
]
在项目目录的urls.py文件添加
from django.urls import path, include
urlpatterns = [
path('quotes/', include('quotes.urls', namespace='quote'))
]
效果图
知识点扩展:
最简单的文件下载功能的实现
将文件流放入HttpResponse对象即可,如
def file_download(request):
# do something...
with open('file_name.txt') as f:
c = f.read()
return HttpResponse(c)
到此这篇关于python中Django文件上传方法详解的文章就介绍到这了,更多相关Django文件上传方法内容请搜索python博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持python博客!
标签:django
Powered By python教程网 鲁ICP备18013710号
python博客 - 小白学python最友好的网站!