返回顶部
扩大
缩小

Gaidy's

Django框架的使用教程--视图和路由[二]

视图和路由

1.创建一个django_test应用

 

2.setting中设置django_test

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_test.apps.DjangoTestConfig'
]

3.在django_test中的view.py中写视图函数

from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse

def index(request):
    return HttpResponse('欢迎来到Gaidy博客')

4.django_test中创建一个urls.py文件用来关联Django目录下的urls.py

from django.conf.urls import url

from . import views


urlpatterns = [
    # 这边定义子应用的路由
    url(r'index/$',views.index)
]

5.Django目录下的urls.py的设置

from django.conf.urls import url,include
from django.contrib import admin
import django_test.urls

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'',include(django_test.urls))
]

6.运行程序

返回html页面

1.在templates创建一个index.html页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Gaidy</title>
</head>
<body>
    这是一个页面
</body>
</html>

2.views.py视图函数修改

from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
from django.shortcuts import render


def index(request):
    return render(request, 'index.html')

    # return HttpResponse('欢迎来到Gaidy博客')

3.运行结果

 视图模板

1.前端页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Gaidy</title>
</head>
<body>
    {{ string }}

</body>
</html>

2.修改view.py代码

from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
from django.shortcuts import render


def index(request):

    date = "我是来自北方的一条狼"

    return render(request, 'index.html', {"string":date})

    # return HttpResponse('欢迎来到Gaidy博客')

3.运行结果

 

posted on 2018-06-30 20:24  Gaidy  阅读(164)  评论(0编辑  收藏  举报

导航