时间:2020-10-13来源:www.pcxitongcheng.com作者:电脑系统城
1、首先在APP目录下创建一个static文件夹
如图:
?1 2 3 4 5 6 7 8 9 10 11 12 |
# Application definition INSTALLED_APPS = [ 'django.contrib.admin' , 'django.contrib.auth' , 'django.contrib.contenttypes' , 'django.contrib.sessions' , 'django.contrib.messages' , 'django.contrib.staticfiles' , 'appBook.apps.AppbookConfig' , ] |
2、在settings.py中 最底部添加如下:
?1 2 3 4 5 6 7 |
# Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = ( os.path.join(BASE_DIR, "appBook/static" ), ) |
3、在html页面头部添加:
?1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
{% load staticfiles %} <!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < title >Title</ title > < link rel = "stylesheet" href = "{% static 'bootstrap/css/bootstrap.css' %}" rel = "external nofollow" > < style > .container{ margin-top: 80px; } </ style > </ head > < body > |
4、在html模版页面,可以用如下方式调用:
?1 2 3 4 5 |
<img src= "{% static 'images/logo.gif' %}" alt= "" /> <img src= "/static/images/acer.gif" alt= "" /> 推荐使用第二种,因为如果图片名称是动态的,可以通过views这么绑定: <img src= "/static/images/{{name}}.gif" alt= "" /> css的引用同样如此: <link rel= "stylesheet" href= "{% static ‘style/base.css' %}" rel= "external nofollow" type = "text/css" > <link rel= "stylesheet" href= "/static/style/base.css" rel= "external nofollow" type = "text/css" > js的引用同样如此: <script type = "text/javascript" src= "{% static ‘js/jquery-1.8.3.min.js' %}" /> <script type = "text/javascript" src= "/static/js/jquery-1.8.3.min.js" /> 可以用 python manage.py findstatic css /index .css 寻找 css |
Django:locals()小技巧
locals()返回一个包含当前作用域里面的所有变量和它们的值的字典。
所以可以把views改写为
?1 2 3 |
def current_datetime(request): current_date = datetime.datetime.now() return render_to_response( 'current_datetime.html' , locals ()) |
这里要注意的是要把now重命名为current_date,因为模板需要的是这个变量名。
在template是如下定义的:
?1 2 3 4 5 |
< html > < body > < font color = "blue" >It is is now {{ current_date }}.</ font > </ body > </ html > |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
2023-03-17
python flask项目打包成docker镜像发布的过程2023-03-17
python调试模块ipdb详解2023-03-17
python使用openai生成图像的超详细教程python cron定时任务触发接口自动化巡检 apscheduler报错:Run time of job …… next run at: ……)” was missed by misfire_grace_time参数 找到任务超时的根本原因...
2023-03-15