最简单的Django文件上传方法[Django框架]
Django上传文件最简单最官方的方法
1.配置media路径
在settings.py中添加如下代码:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
2.定义数据表
import osfrom 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 formsfrom .models import Quote
class QuoteForm(forms.ModelForm):
class Meta:
model = Quote
fields = '__all__'
4.编写视图代码
from django.shortcuts import render, redirectfrom .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, includeurlpatterns = [
path('quotes/', include('quotes.urls', namespace='quote'))
]
效果图
以上是 最简单的Django文件上传方法[Django框架] 的全部内容, 来源链接: utcz.com/z/539904.html