Django3.0入门【3】简单的MTV例子

MTV分别指Model, Template和 View。Model是用来存储数据对象,Template是页面的模板, View是和用户交互的一层视图,起到控制的作用。MTV对应传统MVC,即M -->M, T–>V, V–>C。下面是一个非常典型的MTV例子。

1.手动输入数据(Model部分)

通过输入命令行打开shell

python manage.py shell
>>> from app.models import *
>>> ht = HeroType()
>>> ht.title = '法师'
>>> ht.save()

再去看数据表,发现插入法师数据成功。
在这里插入图片描述
用类似的方法,新增一些数据

>>> from app.models import *
>>> ht = HeroType()
>>> ht.title='刺客'
>>> hero = Hero()
>>> hero.name = '妲己'
>>> hero.gender = '1'
>>> hero.age = '21'
>>> hero.ht = ht
>>> hx = Hero()
>>> hx.name = '韩信'
>>> hx.gender = '0'
>>> hx.age = '22'
>>> hx.ht = ht
>>> ht.save()
>>> hero.save()
>>> hx.save()

2.创建视图控制(View部分)

进入app.view.py中,Django的视图通常都写在这个文件中。我们先

from django.shortcuts import render
from app import models
# Create your views here.

# 设置主页
def index(request):
    '''
    接受用户请求处理业务逻辑
    :param request:
    :return:
    '''

    '''
    找数据 
    '''
    hts = models.HeroType.objects.all() # 把所有英雄类型找出来

    # 构造字典
    ctx = {
        'hts' :hts
    }

    return render(request, 'index.html', ctx) # 利用上下文把数据传到index.html页面上

3.创建一个模板(Template部分)

在项目根目录下创建Template文件夹(如果该文件夹存在,则跳过这一步),并在settings.py里配置Templates的路径,:

# 配置模板
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

现在在templates文件夹下创建一个index.html,并写上内容。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
<h1>欢迎来到王者荣耀</h1>
    <ul>
        <! 这是Django的for写法>
        {% for ht in hts %}
        <li>{{ ht.title }}</li>
        {% endfor %}
    </ul>
</body>
</html>

最后,我们要配置路由。在项目文件夹中(如果按照Django3.0入门【1】的设定,则在xxx文件夹中)中找到urls.py。然后在urlpatterns里增加一个路由路径:path('', views.index),,如下图:

"""untitled URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from app import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index),
]

至此,我们在命令行项目根路径下,输入python manage.py runserver启动服务器,再打开浏览器,输入http://127.0.0.1:8000/,就可以看到如下页面了。至此一个简单地由Django搭建的MTV模型例子就完成了。在这里插入图片描述
下面,我们给法师和刺客做超链接,希望能做到点击英雄类型后跳转到该类型的英雄页面。首先在views.py中新增一个函数showHero(request, id)ID是heroType表中对应的ID,即法师对应’1’,刺客对应’2’。

def showHero(request, id):
    '''
    显示该类英雄
    :param request:
    :param id: 英雄类型主键
    :return:
    '''

    heros = models.Hero.objects.filter(ht=id).all()

    ctx = {
        'hero' : heros
    }
    return render(request, 'heros.html', locals())

修改index.html,增加超链接。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
<h1>欢迎来到王者荣耀</h1>
    <ul>
        <! 这是Django的for写法>
        {% for ht in hts %}
            <li><a href= '/showHeros/{{ ht.id }}/'>{{ ht.title }}</a></li>
        {% endfor %}
    </ul>
</body>
</html>

再在templates中新建一个html页面:heros.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>英雄名-年龄</title>
</head>
<body>
    <ul>
        {% for hero in heros %}
        <li>{{ hero.name }} --- {{ hero.age }}</li>
        {% endfor %}
    </ul>
</body>
</html>

最后要在urls.py中增加一个路由路径:

"""untitled URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from app import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index),
    path('showHeros/<int:id>/', views.showHero),
]

刷新后,我们再看页面:
在这里插入图片描述
法师和刺客变为可点击状态,点击法师后会显示妲己—21,点击刺客后会显示韩信—22。至此小伙伴们可以再体会一下Django的MTV体系。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值