02 理解Django框架下MTV模式(2)

来源:互联网 发布:新疆网络推广 编辑:程序博客网 时间:2024/06/01 10:10

1、概述

本篇用一个简单的示例说明Django的MTV的使用模式,具体前期准备见01内容。

2、步骤1:新建工程

1)在电脑本地新建文件夹,命名Site。

2)打开cmd命令提示符窗口,切换路径至该文件夹。

3)使用django-admin新建工程firstsite

说明:使用命令行后会在Site文件中自动创建,其中firstsite里面的文件结构为:

3、新建一个Django app

1)使用cd切换目录至firstsite中,运行命令python manage.py startapp firstapp

说明:使用命令后会产生firstapp文件夹,里面的文件内容就包含M、V结构(注意:T结构是网页模板,这个示例中用html语句替代):

2)用Atom打开该文件,往firstsite的setting.py中添加firstapp

INSTALLED_APPS = [    'django.contrib.admin',    'django.contrib.auth',    'django.contrib.contenttypes',    'django.contrib.sessions',    'django.contrib.messages',    'django.contrib.staticfiles',    'firstapp',   #添加内容]

4、创建数据库

1)合并、运行数据库

说明:使用python manage.py makemigrations和python manage.py migrate产生默认数据库(db.sqlite3),这与setting中的数据库设置有关:

DATABASES = {    'default': {        'ENGINE': 'django.db.backends.sqlite3',        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),    }}
2)运行服务

使用python manage.py runserver就可以将django网站发布到本地。

说明:如上所示,django网站已经可以访问,只是没有内容。

5、在models.py中创建数据表

from django.db import models# Create your models here.class People(models.Model):    name = models.CharField(null=True, blank=True, max_length=200)    job = models.CharField(null=True, blank=True, max_length=200)
说明:在创建完数据表后,就要使用4中的数据库合并两条语句,才能把数据写到数据库中。

6、在view.py中引入模型的数据

from django.shortcuts import render, HttpResponsefrom firstapp.models import Peoplefrom django.template import Context, Template# Create your views here.def first_try(request):    person = People(name='Spock', job='officer') #初始化People一个数据    html_string = '''<html>            <head>                <meta charset="utf-8">                <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.6/semantic.css" media="screen" title="no title">                <title>firstapp</title>            </head>            <body>                <h1 class="ui center aligned icon header">                    <i class="hand spock icon"></i>                    Hello, {{ person.name }}                </h1>            </body>        </html>    '''    t = Template(html_string)    c = Context({'person':person})  #构造模板与数据连接    web_page = t.render(c)  #模板渲染,此时为本文格式    return HttpResponse(web_page)   #返回为网页格式
说明:设计了一个first_try函数是用来使模板html_string引入数据库的数据,通过模板变量{{ person.name }}。

7、在url.py中分配网址

from django.conf.urls import urlfrom django.contrib import adminfrom firstapp.views import first_tryurlpatterns = [    url(r'^admin/', admin.site.urls),    url(r'^first_try/', first_try),]
说明:在开头要引入view中定义的视图first_try;在url(r'^....)中的r'^是本地网址http://127.0.0.1:8000/,实际中加first_try即可访问,first_try视图表现的内容:



原创粉丝点击