Django 读取静态文件图片

Django 读取静态文件图片

实现需求 http://127.0.0.1:8000/student/hello/1.png 获取图片资源

#配置 test33/urls.py
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^student/',include('stu.urls'))
]
#配置 stu/urls.py

urlpatterns = [
    url(r'^$',views.IndexView.as_view()),
    url(r'^hello/(.*)$',views.StaticView.as_view())
]

#配置 views.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.http import HttpResponse, Http404, FileResponse
from django.shortcuts import render

# Create your views here.
from django.views import View


class StaticView(View):
    def get(self,request,*args, **kwargs):
        import re
        import os
        #获取图片路径,返回 /student/hello/1.png
        filepath = request.path
        print filepath

        #获取图片名 1.png
        m=re.match(r'/student/hello/(.*)',filepath)
        filename = m.group(1)
        print filename

        #获取磁盘图片路径 F:pycharmexec	est33staticimages1.png
        filedir = os.path.join(os.getcwd(),'static\images',filename)
        print filedir
        if not os.path.exists(filedir):
            raise Http404
        else:
            return FileResponse(open(filedir,'rb'),content_type='*/*')  

页面嵌套图片

需求: 访问 http://127.0.0.1:8000/student/ 页面嵌套图片

# 修改setting.py 末尾增加:
STATICFILES_DIRS = [
    os.path.join(BASE_DIR,'staticimages'),
    os.path.join(BASE_DIR,'staticcss'),
    os.path.join(BASE_DIR,'staticjs'),
]

# 修改urls.py
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^student/',include('stu.urls'))
]
#修改 stu/urls.py
from django.conf.urls import url
import views

urlpatterns = [
    url(r'^$',views.IndexView.as_view()),
    url(r'^hello/(.*)$',views.StaticView.as_view()),

]

# 修改views.py
class IndexView(View):
    def get(self, request, *args, **kwargs):
        return render(request,'index.html')
    def post(self, request, *args, **kwargs):
        return HttpResponse('POST请求')

#新增加 templates/index.html

{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="{% static 'my.css' %}" type="text/css"/>
    <script type="text/javascript" src="{% static 'my.js' %}"></script>
</head>
<body>
    <img src="/static/1.png"/>
    <img src="{% static '1.png' %}"/>
<form action="/student/" method="post">
         {% csrf_token %}
        <input type="submit" id="btn"/>
</form>

</body>
</html>

#新增加 static/css/my.css
img{
    border:3px solid red;
}

#新增加 static/js/my.js
window.onload = function(){
    alert('hello')
    document.getElementById('btn').onclick = function(){
        alert('haha')
    }
}


图片直接访问方式

原文地址:https://www.cnblogs.com/lixinliang/p/14118741.html