zoukankan      html  css  js  c++  java
  • Django(三)url和返回

    location 最后一个文件夹名就是project名,我用了Django_Plan。

    Application 是自动加入的APP名字,我用了Plan

    编辑Django_PlanDjango_Planurls.py

    from django.contrib import admin
    from django.urls import path
    from Plan import views

    urlpatterns = [
    path('admin/', admin.site.urls),
    path('plan', views.plan) #此行为增加的
    ]

    编辑Django_PlanPlanviews.py

    from django.shortcuts import render
    from django.shortcuts import HttpResponse  #此行增加
    # Create your views here.
    def plan(request):                   #此函数增加
        return HttpResponse('hello')

    好了,我们增加了一个url解析,解析到plan函数,进行http返回给浏览器。

    试一下,浏览器http://localhost:8000/plan,会看到hello。用的是HttpResponse函数。

    平时访问的页面那么多内容,我们不能都写在HttpResponse中呀。

    我们用模板吧。

    建立一个hello.html文件放在Django_Plan emplateshello.html

    内容为:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Hello</title>
    </head>
    <body>
    <h1>hello</h1>    
    </body>
    </html>

    编辑Django_PlanPlanviews.py

    from django.shortcuts import render
    from django.shortcuts import HttpResponse  #此行增加
    # Create your views here.
    def plan(request):                   #此函数增加
        return render(request,'hello.html')

    检查Django_PlanDjango_Plansettings.py(难道我用最新的django2.0,pycharm就不自动创建了?)

    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',
                ],
            },
        },
    ]

    好了,这下浏览器返回的就是我们的模板文件内容,h1格式的hello

    我们还需要动态生成页面,继续编辑hello.html,给输出的hello加上两个大括号

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

    编辑Django_PlanPlanviews.py

    from django.shortcuts import render
    from django.shortcuts import HttpResponse  #此行增加
    # Create your views here.
    def plan(request):                   #此函数增加
        return render(request,'hello.html',{'hello':'hello jack'})

    这里就是在render的参数中又加了一个字典,把hello换成hello jack,再返回给客户端浏览器。

    打开页面试试吧。

  • 相关阅读:
    一本名副其实的 Web架构“圣经”——关于《HTTP权威指南》
    图灵生日会——纪念阿兰图灵诞辰100周年及图灵公司七周年线下交流会
    跟着图灵听课去!(六月)
    “电梯演讲”最精炼、贴切的语言
    送你一把开启演讲之路的钥匙——《演讲的艺术》
    翻译是一份严谨的工作——关于HTTP中文翻译的讨论
    浪潮之巅作者吴军推荐序——《推荐系统实践》
    如何到达永生?揭示科学之美
    软件行业大牛告诉你何谓成功?
    C#线程系列讲座(3):线程池和文件下载服务器
  • 原文地址:https://www.cnblogs.com/jackadam/p/8094093.html
Copyright © 2011-2022 走看看