如何呈现HTML模板?

时间:2018-04-26 09:57:12

标签: python django

我正在研究这种方法(来自Antonio Mele写的书)

~/mysite/blog$ ls
admin.py  apps.py  __init__.py  migrations  models.py  __pycache__  tests.py  views.py

OP说我们将创建HTML模板来渲染生成的数据 由观点。我不明白这。这是博客文件夹ls输出

cat views.py 
from django.shortcuts import render

这是视图的样子

public class Book
    {
        [Key]
        public int BookId { get; set; }
        public string Name { get; set; }
        public string AuthorName { get; set; }
        public int YearOfPublishing { get; set; }
        public LibraryType Type { get; set; }

        public  ICollection<BookPublicHouse> BookPublicHouses { get; set; }

        public Book()
        {
            BookPublicHouses = new Collection<BookPublicHouse>();
        }

    }



public class PublicHouse
{
    [Key]
    public int PublicHouseId { get; set; }

    public string PublicHouseName { get; set; }

    public string Country { get; set; }

    public ICollection<BookPublicHouse> BookPublicHouses { get; set; }

    public PublicHouse()
    {
        BookPublicHouses = new Collection<BookPublicHouse>();
    }
}

在这个例子中,我无法理解post和views.py之间的链接。

1 个答案:

答案 0 :(得分:1)

当您在相应的网址上发布一些数据时,将运行view.py和post方法中的代码。请看一下以下片段:

def post_list(request):          # http://127.0.0.1:8000/myurl
    if request.method == 'POST':
        # process the posted data if you wish to by
        # posted_data = request.data
        posts = Post.published.all()
        return render(request,'blog/post/list.html',{'posts': posts})

在上述情况下,您必须将html模板文件存储在template / app_name / html_file.html目录中。因此,当您的post方法执行时,它将返回该html_file.html文件并向其添加上下文,如下所示:

context = {"posts": posts}
            return render(request, "video_response.html", context)

您必须在html_file.html中添加{{posts}}以获取在views.py的post方法中呈现的数据