0day-从实验楼开始

Django文件结构

设计模型Model - models.py

#myProject/myApp/models.py
form django.db import models
class book(models.Model):
    name = models.CharField(max_length=100)
    pub_date = models.DateField()

设计视图Views - views.py

# myProject/myApp/views.py
from django.shortcuts import render
from .models import Person

def book_archive(request, year):
    book_list = Person.objects.filter(birth_year = year)
    context = {'year': year, 'book_list': book_list}
    return render(request, 'books/year_archive.html', context)

设计链接Urls - urls.py

# myProject/myApp/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('books/', views.year_archive),
]

设计模板Templates - year_archive.html

# /template/year_archive.html
{% block title %}Books for {{ year }}{% endblock %}

{{% block content %}}

Articles for {{years}}

{% for book in book_list %}

{{ book.name }}

Published {{ book.pub_date|date:"F j, Y" }}

{% endfor %} {% end block %}

Django的这种结构我们称之为MTV模式:M代表模型(Model),T代表模板(Template),V代表视图(View)。这三个分别代表了三种不同功能的Web应用,各司其职,又彼此合作。 大家一定听说过MVC模式(Mode-View-Controller),MTV模式本质上与MVC相同,都是让各组件保持低耦合的关系。 关于MTV模式我们将在后面部分详细的讲解。

你可能感兴趣的:(0day-从实验楼开始)