0
点赞
收藏
分享

微信扫一扫

计算机体系结构重点学习

编程练习生J 2024-06-15 阅读 29

使用通用视图的好处是:如果有一个html需要展示,不需要写view视图函数,直接写好url即可。

使用通用视图的步骤如下:

1、编辑项目urls.py文件

    from django.views.generic import TemplateView

在该文件的映射表中添加:

    path('home/', TemplateView.as_view(template_name="home.html"), name='home'),

2、在项目templates目录下,新建home.html文件

    {% extends "base.html" %}
    {% block title %}Home page{% endblock %}
    {% block content %}
    <div class="text-center">
        <h1>WELCOM YOU</h1>
        <h3>Life is short. You need Python</h3>
        <h2>Django makes it easier to build better Web apps more quickly and with less
    code.</h2>
        {% load staticfiles %}
        <img src="{% static 'images/book.jpg' %}">
    </div>
    {% endblock %}

其中base.html文件同样位于项目templates目录下。book.jpg文件位于项目的static\images目录下。

3、打开网页http://localhost:8000/home/,即可查看。

4、在html文件中使用这个url时,方法如下:

<li><a href="{% url 'home' %}">HOME</a></li>

注意{% url 'home'%}的home前没有子项目名称。

举报

相关推荐

0 条评论