Anaconda+django写出第一个web app(四)

前面对Models有了一些了解,今天开始进一步了解Views,了解Views如何和Models交互以及了解模板(templates)。

打开main文件夹下的views.py,重新编写homepage函数,render的用法可在帮助文档 [1]中查看:

from django.shortcuts import render
from django.http import HttpResponse
from .models import Tutorial
# Create your views here.
def homepage(request):
    return render(request=request, 
            template_name='main/home.html',
            context={'tutorials':Tutorial.objects.all})

django会在你的app文件夹下寻找名称为"templates"的文件夹,为了避免有时模板重名的问题,我们在templates文件夹下在建立一个名称为main的文件夹。也就是mysite/main/templates/main。然后在这个文件夹下放置我们的html文件,新建home.html,并写入如下内容:

{% for t in tutorials %}
    <p>{{ t.tutorial_title }}</p>
    <p>{{ t.tutorial_published }}</p>
    <p>{{ t.tutorial_content }}</p>
  <br><br>
{% endfor %}

注意这里的for t in tutorials中的tutorials和views.py中的context={’tutorials': Tutorial.objects.all}中的tutorials时对应的。

我们进入admin添加一个名为‘WriteCode’,内容为如上html的内容的tutorial。保存后进入主页http://127.0.0.1:8000/,看到如下页面:

 可以看到我们之前建立的两个tutorial的标题、时间、内容。但是第二个内容显示很乱,如何让其显示正常呢?只需要将home.html中的t.tutorial_context改为t.tutorial_context|safe即可,修改后显示如下:

 此时虽然代码显示整齐了,但是没有代码高亮显示,如何让代码高亮显示呢?我们需要引入CSS/js,我们在安装TinyMCE时,就有了相应的CSS/js,我们只需引用即可。那么如何应用呢?django默认会在static的文件夹下寻找,就像在templates文件夹下寻找html文件一样,文件路径APPNAME/tinymce/APPNAME/。我们在使用之前需要先载入static文件夹,修改home.html文件:

{% load static %}
<link href="{% static 'tinymce/css/prism.css' %}" rel="stylesheet">
</head>
<body>

{% for t in tutorials %}
    <p>{{ t.tutorial_title }}</p>
    <p>{{ t.tutorial_published }}</p>
    <p>{{ t.tutorial_content|safe }}</p>
    <br><br>
{% endfor %}

<script src="{% static 'tinymce/js/prism.js' %}"></script>
</body>

显示效果如下,代码有了相应的颜色:

扫描二维码关注公众号,回复: 5261420 查看本文章

这一部分开始接触一些html语言,需要自己查阅相关教程进行学习。

参考链接:

[1] https://docs.djangoproject.com/zh-hans/2.1/topics/http/shortcuts/

[2] https://pythonprogramming.net/views-templates-django-tutorial/?completed=/admin-apps-django-tutorial/

猜你喜欢

转载自www.cnblogs.com/yunxiaofei/p/10415919.html