zoukankan      html  css  js  c++  java
  • 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.运行结果

    皮豆设计(logo设计神器):http://pidou.cn

  • 相关阅读:
    Linux 系统启动过程
    Linux启动U盘制作
    JSONP 教程
    JSON 使用
    JSON.stringify()
    JSON.parse()
    Apache模块开发指南-APR池
    [C++基础]goto的用法
    atexit()函数
    c++ good books
  • 原文地址:https://www.cnblogs.com/gaidy/p/9248535.html
Copyright © 2011-2022 走看看