最简单的Django文件上传方法
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')) ]
效果图
准备工作1.注册微博开放者平台并通过个人认证,创建一个网页应用。2.在高级信息中编辑回掉url,可以填写本机的地址。3.找到自己的app_key 和 App Secret并保存。 ...