Bootstrap

Django-文件上传

定义:

上传规则-前端【html】:

上传规则-后端【Django】:

urlpatterns = [
  
    path('upload',views.test_upload)
]

例子:

settings添加:

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

主路由:

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

分路由:

urlpatterns = [
  
    path('upload',views.test_upload)
]

models:


class Content(models.Model):
    title = models.CharField('标题', max_length=100)
    picture = models.FileField(upload_to='picture')

views:

def test_upload(request):
    if request.method == 'POST':
        file = request.FILES.get('file')
        title = request.POST.get('title')
        Content.objects.create(title=title,file=file)
        return HttpResponse('上传成功')
    elif request.method == 'GET':
        return render(request,'node/test_upload.html')

 

;