使用Code开发Django_模版和CSS

转到定义 和 查看定义

在使用Django或任何其他库的过程中,我们可能需要检查这些库中的代码。VS Code提供了两个方便的命令,可以直接导航到任何代码中的类和其他对象的定义:

  • 转到定义 在Python开发环境中,我们可以轻松地对函数、类或者其他导入模块中的成员使用“Go to Definition”,以便深入研究其内部实现。这一功能对于调试、重构代码以及学习他人代码库特别有用。 当点击或使用快捷键激活此功能时,Code会直接跳转到源代码中该符号被首次声明或定义的位置,这有助于程序员理解代码的工作原理以及如何被实现。例如,在文件 views.py中, 右击 home 函数中的 HttpResponse 选择 Go to Definition (快捷键F12), Code打开Django的库,显示HttpResponse的定义。如截屏

  • 查看定义 (Alt+F12和右键菜单), “Peek Definition”可以帮助我们快速查看某个函数或类的定义,同时保持对当前代码编辑位置的关注,这样就可以在不离开当前工作区的情况下了解相关代码结构和实现细节。相关定义的代码直接在当前文件内显示,并不单独单开文件,退出方式: ESC键,右上角的关闭按钮。

    Django tutorial: Peek Definition showing the Flask class inline

使用模板生成网页

上个例子中我们仅仅创建了简单的文字网页.  我们还需要构建更复杂的网页,虽然可以通过代码直接生成HTML,但是开发人员一般不会如此操作,从而可以避免网站受到XSS攻击(cross-site scripting (XSS) attacks.) 

一个更好是使用实践是,在编程过程中不使用HTML文件,用templates来代替。这样的话在程序中只需要考虑数据而不需要考虑格式。

Django中的模版是包含数据占位符的HTML文件。程序运行时,Django模板引擎负责在呈现页面时进行数据和占位符之间的替换,并提供自动转义以防止XSS攻击(也就是说,如果您尝试在数据值中使用HTML,则会看到HTML仅以纯文本形式呈现)。这样的设计下,代码只关心数据值,而模板只关心标记(占位符)。Django模板提供了灵活的选项,如模板继承,它允许我们定义一个带有公共标记的基础页,然后在该基础页上添加特定的页面内容。

本章节中,我们先采用模版创建一个单页。然后通过CSS文件进行相关的格式配置,和含有公共标记的多页模版。Django模版还支持 Controll flow(控制流,编程)和iteration(迭代)

  1. 修改 web_project/settings.py 文件, 在 INSTALLED_APPS 表中增加下面的输入。该输入的作用是确保项目知道hello这个app的存在。

    'hello',
    
  2. hello 文件夹内创建templates文件夹, 在templates中创建子目录 hello 与app名字保持一致 (两级目录结构是经典的Django结构convention).

  3. 在 templates/hello 目录中, 创建文件 hello_there.html 内容如下. 该模版包含两个数据占位符名字为“name”和“date”。占位符用两个花括号表示{{ and }}. 其他内容为标砖的HTML文件格式。 模版占位符也可以在管道(pipe)符号"|"后包含格式 。在本利中使用Django内置的 date filter 和 time filter,在代码中可以仅传递datetime的数值,不需要考虑格式。

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8" />
            <title>Hello, Django</title>
        </head>
        <body>
            <strong>Hello there, {{ name }}!</strong> It's {{ date | date:"l, d F, Y" }} at {{ date | time:"H:i:s" }}
        </body>
    </html>
    
  4. 在 views.py文件的头部,增加下面的程序行:

    from django.shortcuts import render
    
  5. views.py文件中,修改 hello_there 函数,使用 django.shortcuts.render 方法来加载模版 template 并提供模版上下文。这里的上下文是指在template中占位符所规定的参数集。Render函数包含三个参数, request, templates的路径和文件,上下文内容。 (开发者通常对让模版和使用它们的函数保持相同的命名。相同的名字在Django中不是必须的。)

    def hello_there(request, name):
        print(request.build_absolute_uri()) #optional
        return render(
            request,
            'hello/hello_there.html',
            {
                'name': name,
                'date': datetime.now()
            }
        )
    

    上述的代码比较简单,仅仅关注数据,相关的的格式在template中定义。#前后端分离 #解耦

  6. 启动程序(可以使用debug,或者不使用debugger Ctrl+F5)浏览器进入 /hello/name , 检查结果。

  7. Also try navigating to a /hello/name URL using a name like <a%20value%20that%20could%20be%20HTML> to see Django's automatic escaping at work. The "name" value shows up as plain text in the browser rather than as rendering an actual element. // 这个功能并没有效果

回顾:

  1. 项目中的settings.py文件增加 installed app
  2. 建立对应的templates目录结构和html模版文件,为数据准备占位符
  3. 修改app的view.py文件中对应函数(原则上与html文件保持一致),采用Render函数给对应的html文件占位符提供数据。

CSS文件的使用

静态文件是web应用程序为某些请求(如CSS文件)原样返回的内容片段。提供静态文件要求settings.py中的INSTALLED_APPS列表包含django.contrib.staticfiles,默认情况下会包含该列表。

在Django中提供静态文件是一门艺术,尤其是在部署到生产环境中时。这里展示的是一种简单的方法,它适用于Django开发服务器和像Gunicorn这样的生产服务器。然而,静态文件的完整处理超出了本教程的范围,更多信息,请参阅Django文档中的管理静态文件Managing static files 
切换到生产时,导航到settings.py,设置DEBUG=False,然后更改ALLOWED_HOSTS=['*']以允许特定主机。在使用容器时,这可能会导致额外的工作。有关详细信息,请参阅 Issue 13.

 为APP准备静态文件

  1. 项目文件 web_project/urls.py, 增加下面的导入信息:

    from django.contrib.staticfiles.urls import staticfiles_urlpatterns
    
  2. 相同文件内的底部增加下面的语句。目的,CSS文件的URL增加到项目可识别的URL列表中:

    urlpatterns += staticfiles_urlpatterns()
    

在模版中引用CSS

  1. hello 目录中, 创建目录 static.

  2.  static 目录总, 创建子目录 hello, matching the app name.

    The reason for this extra subfolder is that when you deploy the Django project to a production server, you collect all the static files into a single folder that's then served by a dedicated static file server. The static/hello subfolder ensures that when the app's static files are collected, they're in an app-specific subfolder and won't collide with file from other apps in the same project.

  3. In the static/hello folder, create a file named site.css with the following contents. After entering this code, also observe the syntax highlighting that VS Code provides for CSS files, including a color preview.

    .message {
        font-weight: 600;
        color: blue;
    }
    
  4. In templates/hello/hello_there.html, add the following lines after the <title> element. The {% load static %} tag is a custom Django template tag set, which allows you to use {% static %} to refer to a file like the stylesheet.

    {% load static %}
    <link rel="stylesheet" type="text/css" href="{% static 'hello/site.css' %}" />
    
  5. Also in templates/hello/hello_there.html, replace the contents <body> element with the following markup that uses the message style instead of a <strong> tag:

    <span class="message">Hello, there {{ name }}!</span> It's {{ date | date:'l, d F, Y' }} at {{ date | time:'H:i:s' }}.
    
  6. Run the app, navigate to a /hello/name URL, and observe that the message renders in blue. Stop the app when you're done.

Use the collectstatic command

For production deployments, you typically collect all the static files from your apps into a single folder using the python manage.py collectstatic command. You can then use a dedicated static file server to serve those files, which typically results in better overall performance. The following steps show how this collection is made, although you don't use the collection when running with the Django development server.

  1. In web_project/settings.py, add the following line that defines a location where static files are collected when you use the collectstatic command:

    STATIC_ROOT = BASE_DIR / 'static_collected'
    
  2. In the Terminal, run the command python manage.py collectstatic and observe that hello/site.css is copied into the top level static_collected folder alongside manage.py.

  3. In practice, run collectstatic any time you change static files and before deploying into production.

Create multiple templates that extend a base template

Because most web apps have more than one page, and because those pages typically share many common elements, developers separate those common elements into a base page template that other page templates then extend. (This is also called template inheritance, meaning the extended pages inherit elements from the base page.)

Also, because you'll likely create many pages that extend the same template, it's helpful to create a code snippet in VS Code with which you can quickly initialize new page templates. A snippet helps you avoid tedious and error-prone copy-paste operations.

The following sections walk through different parts of this process.

Create a base page template and styles

A base page template in Django contains all the shared parts of a set of pages, including references to CSS files, script files, and so forth. Base templates also define one or more block tags with content that extended templates are expected to override. A block tag is delineated by {% block <name> %} and {% endblock %} in both the base template and extended templates.

The following steps demonstrate creating a base template.

  1. In the templates/hello folder, create a file named layout.html with the contents below, which contains blocks named "title" and "content". As you can see, the markup defines a simple nav bar structure with links to Home, About, and Contact pages, which you create in a later section. Notice the use of Django's {% url %} tag to refer to other pages through the names of the corresponding URL patterns rather than by relative path.

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8"/>
        <title>{% block title %}{% endblock %}</title>
        {% load static %}
        <link rel="stylesheet" type="text/css" href="{% static 'hello/site.css' %}"/>
    </head>
    
    <body>
    <div class="navbar">
        <a href="{% url 'home' %}" class="navbar-brand">Home</a>
        <a href="{% url 'about' %}" class="navbar-item">About</a>
        <a href="{% url 'contact' %}" class="navbar-item">Contact</a>
    </div>
    
    <div class="body-content">
        {% block content %}
        {% endblock %}
        <hr/>
        <footer>
            <p>&copy; 2018</p>
        </footer>
    </div>
    </body>
    </html>
    
  2. Add the following styles to static/hello/site.css below the existing "message" style, and save the file. (This walkthrough doesn't attempt to demonstrate responsive design; these styles simply generate a reasonably interesting result.)

    .navbar {
        background-color: lightslategray;
        font-size: 1em;
        font-family: 'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif;
        color: white;
        padding: 8px 5px 8px 5px;
    }
    
    .navbar a {
        text-decoration: none;
        color: inherit;
    }
    
    .navbar-brand {
        font-size: 1.2em;
        font-weight: 600;
    }
    
    .navbar-item {
        font-variant: small-caps;
        margin-left: 30px;
    }
    
    .body-content {
        padding: 5px;
        font-family:'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }
    

You can run the app at this point, but because you haven't made use of the base template anywhere and haven't changed any code files, the result is the same as the previous step. Complete the remaining sections to see the final effect.

Create a code snippet

Because the three pages you create in the next section extend layout.html, it saves time to create a code snippet to initialize a new template file with the appropriate reference to the base template. A code snippet provides a consistent piece of code from a single source, which avoids errors that can creep in when using copy-paste from existing code.

  1. In VS Code, select the File (Windows/Linux) or Code (macOS), menu, then select Preferences > User snippets.

  2. In the list that appears, select html. (The option may appear as "html.json" in the Existing Snippets section of the list if you've created snippets previously.)

  3. After VS code opens html.json, add the code below within the existing curly braces. (The explanatory comments, not shown here, describe details such as how the $0 line indicates where VS Code places the cursor after inserting a snippet):

    "Django Tutorial: template extending layout.html": {
        "prefix": "djextlayout",
        "body": [
            "{% extends \"hello/layout.html\" %}",
            "{% block title %}",
            "$0",
            "{% endblock %}",
            "{% block content %}",
            "{% endblock %}"
        ],
    
        "description": "Boilerplate template that extends layout.html"
    },
    
  4. Save the html.json file (Ctrl+S).

  5. Now, whenever you start typing the snippet's prefix, such as djext, VS Code provides the snippet as an autocomplete option, as shown in the next section. You can also use the Insert Snippet command to choose a snippet from a menu.

For more information on code snippets in general, refer to Creating snippets.

Use the code snippet to add pages

With the code snippet in place, you can quickly create templates for the Home, About, and Contact pages.

  1. In the templates/hello folder, create a new file named home.html, Then start typing djext to see the snippet appear as a completion:

    Django tutorial: autocompletion for the djextlayout code snippet​​

    When you select the completion, the snippet's code appears with the cursor on the snippet's insertion point:

    Django tutorial: insertion of the djextlayout code snippet​​

  2. At the insertion point in the "title" block, write Home, and in the "content" block, write <p>Home page for the Visual Studio Code Django tutorial.</p>, then save the file. These lines are the only unique parts of the extended page template:

  3. In the templates/hello folder, create about.html, use the snippet to insert the boilerplate markup, insert About us and <p>About page for the Visual Studio Code Django tutorial.</p> in the "title" and "content" blocks, respectively, then save the file.

  4. Repeat the previous step to create templates/hello/contact.html using Contact us and <p>Contact page for the Visual Studio Code Django tutorial.</p>.

  5. In the app's urls.py, add routes for the /about and /contact pages. Be mindful that the name argument to the path function defines the name with which you refer to the page in the {% url %} tags in the templates.

    path("about/", views.about, name="about"),
    path("contact/", views.contact, name="contact"),
    
  6. In views.py, add functions for the /about and /contact routes that refer to their respective page templates. Also modify the home function to use the home.html template.

    # Replace the existing home function with the one below
    def home(request):
        return render(request, "hello/home.html")
    
    def about(request):
        return render(request, "hello/about.html")
    
    def contact(request):
        return render(request, "hello/contact.html")
    

Run the app

With all the page templates in place, save views.py, run the app, and open a browser to the home page to see the results. Navigate between the pages to verify that the page templates are properly extending the base template.

Django tutorial: app rendering a common nav bar from the base template​​

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/526329.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

【QT学习】Graphics View框架(高阶篇)- 使用Graphics View框架创建开机动画

【QT学习】Graphics View框架&#xff08;高阶篇&#xff09;- 使用Graphics View框架创建开机动画_qgraphicsview 一步-CSDN博客 前言 在上一篇《Graphics View框架&#xff08;进阶篇&#xff09;- 派生QGraphicsItem类创建自定义图元item》中&#xff0c;我们介绍了创建自定…

助力AIGC暴雨推出4卡液冷图站TR770

2022年&#xff0c;ChatGPT横空出世&#xff0c;正式拉开了生成式人工智能&#xff08;AIGC&#xff09;的序幕&#xff1b;2024年&#xff0c;Sora惊艳亮相&#xff0c;再度将AIGC技术推向高潮&#xff0c;引发了全球范围内的新一轮科技竞赛与创新热潮。从文字创作的灵感迸发&…

图像处理环境配置opencv-python

下载python&#xff0c;配置pip使用清华源下载镜像&#xff1a; pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple 切换到python目录下&#xff0c;右击cmd&#xff0c;执行pip升级指令: python -m pip install --upgrade pip 下载opencv&#x…

“鲜花换冥币,文明寄哀思“张家口慈善义工联合会清明节活动

又是一年春草绿&#xff0c;梨花风起正清明。扫墓祭祖、缅怀先人是清明节的重要民俗活动&#xff0c;为摒弃传统陋习&#xff0c;树文明祭祀新风&#xff0c;2024年4月4日&#xff0c;张家口慈善义工联合会携手市人民公墓西祥园组织志愿者们开展以“鲜花换冥币&#xff0c;文明…

windows下使用的的数字取证工作工具套装:forensictools

推荐一套windows下使用的的数字取证工作工具套装&#xff1a;forensictools 部分工具包括&#xff1a; ▫️exiftool&#xff0c;一个命令行应用程序和 Perl 库&#xff0c;用于读写元信息。 ▫️YARA&#xff0c;一款开源工具&#xff0c;用于对恶意软件样本进行识别和分类。…

开源区块链系统/技术 总结(欢迎补充,最新)

1. FISCO BCOS FISCO BCOS 2.0 技术文档 — FISCO BCOS 2.0 v2.9.0 文档https://fisco-bcos-documentation.readthedocs.io/ 2. ChainMaker&#xff08;长安链&#xff09; 文档导航 — chainmaker-docs v2.3.2 documentationhttps://docs.chainmaker.org.cn/v2.3.2/html/in…

移动机器人运动规划 | 基于图搜索的Dijkstra 和 A*算法详解

Dijkstra 算法 Dijkstra 算法与BFS算法的区别就是 : 从容器中弹出接下来要访问的节点的规则不同 BFS 弹出: 层级最浅的原则&#xff0c;队列里最下方的元素 Dijkstra 弹出: 代价最小的节点g(n) g(n) :表示的是从开始节点到当前n节点的代价累加 Dijkstra在扩展的时候&#x…

深度挖掘商品信息,jd.item_get API助您呈现商品全面规格参数

深度挖掘商品信息&#xff0c;特别是在电商平台上&#xff0c;对于商家、开发者和用户来说都至关重要。jd.item_get API作为京东开放平台提供的一个强大工具&#xff0c;能够帮助用户轻松获取商品的全面规格参数&#xff0c;进而为商品分析、推荐、比较等提供有力的数据支撑。 …

arm64 - 系统调用

起因 群里做网络的小伙伴问了一个问题&#xff0c;他在wifi驱动的某个函数里加了dump stack&#xff0c;然后插入驱动&#xff0c;发现调用栈是这样的&#xff0c;为什么呢&#xff1f; 代码追溯 insmod这个app&#xff0c;是在busybox中的&#xff0c;所以找到busybox的代…

大话设计模式——13.外观模式(Facade Pattern)

简介 又称门面模式&#xff0c;为子系统中的一组接口提供一个一致的界面&#xff0c;外观模式定义了一个高层接口&#xff0c;这个接口使得这一子系统更加容易使用。 UML图 应用场景&#xff1a; 第三方SDK大多使用该模式&#xff0c;通过一个外观类&#xff0c;可对用户屏蔽…

蓝桥杯DFS-最大数字

解题思路 我们从最高位开始要利用自己的1号操作和2号操作保证当前这个数位的数一定要尽可能最大。 然后分别考虑两种操作&#xff0c;首先两种操作不可能混用&#xff0c;因为它们是抵消的效果&#xff0c;所以要么对这个数全使用1操作&#xff0c;要么2操作。假设某个数位的…

easyexcel处理复杂表头

需求&#xff0c;模板如下 功能如下 开始整活&#xff0c;依赖包。 <dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>3.2.1</version> </dependency>下载导入模板 1.方法 GetMapping…

详解FB广告三种受众类型,提升广告投放精准度

在Facebook广告中&#xff0c;精确地定位潜在客户至关重要。然而&#xff0c;达到完美精准度通常是一个逐渐逼近的过程&#xff0c;涉及到多次迭代和细化目标人群。Facebook提供了三种主要的受众类型&#xff1a;核心受众(Core Audiences)、自定义受众(Custom Audiences)和类似…

携手博鳌亚洲论坛,五粮液“以和美,敬世界”

执笔 | 尼 奥 编辑 | 扬 灵 3月26-29日&#xff0c;以“亚洲与世界&#xff1a;共同的挑战 共同的责任”为主题的博鳌亚洲论坛2024年年会在海南博鳌盛大召开&#xff0c;聚集全球政商学媒等各国代表汇聚一堂&#xff0c;围绕投资亚洲未来、减少贸易碎片化、加速迈向零碳电…

朗汀留学美国生物医学工程专业留学部分录取案例合集

满怀期待的憧憬与金榜题名的喜悦交织着未来的掌声&#xff0c;捧在手心里的不仅仅是一份一份努力浇灌的录取通知&#xff0c;更是一起拼搏走过的岁月沉淀。 我们感恩每一位朗汀留学的学生和家长&#xff0c;是你们的支持与信任&#xff0c;让我们有机会共享此刻的荣耀&#xff…

初涉 VS Code 插件开发

官方文档&#xff1a;Extension API | Visual Studio Code Extension API 实战记录 从hello word&#xff01;开撕 根据文档开始创建插件 Your First Extension | Visual Studio Code Extension API 全局安装Yeoman工具 npm install --global yo generator-code 使用Yeom…

nginx 配置访问地址和解决跨域问题(反向代理)

1、配置访问地址&#xff08;通过ip访问&#xff09; //配置ip访问地址 location ^~/auditApp{alias /usr/local/front-apps/cbd/auditApp;index index.html;if (!-e $request_filename) {rewrite ^/(.*) /auditApp/index.html last;break;}} 2、解决跨域问题&…

二叉树后序遍历算法多种实现傻傻分不清楚

致力于C、C、Java、Kotlin、Android、Shell、JavaScript、TypeScript、Python等编程技术的技巧经验分享。 若作品对您有帮助&#xff0c;请关注、分享、点赞、收藏、在看、喜欢。您的支持是我们为您提供帮助的最大动力。 1.介绍 二叉树的后序遍历是一种遍历二叉树的策略&#…

运行v3+ts+vite+eslint碰到的问题集合

1、问题&#xff1a;提示Missing semicolon semi&#xff08;缺少分号&#xff09; 解决&#xff1a;对比其他ts代码&#xff0c;发现在orderDetail后少了分号&#xff0c;加上去之后就可以了。好严格&#xff01;&#xff01;&#xff01; 2、问题&#xff1a;The template…

idea开发 java web 疫情信息查询系统bootstrap框架web结构java编程计算机网页接口查询

一、源码特点 java 疫情信息查询系统是一套完善的完整信息系统&#xff0c;结合java web开发和bootstrap UI框架完成本系统 &#xff0c;对理解JSP java编程开发语言有帮助&#xff0c;系统具有完整的源代码和数据库&#xff0c;系统主要采用B/S模式开发。 前段主要技术 css j…