zoukankan      html  css  js  c++  java
  • Django学习之-带参数的路由应用

    一、简单使用

    浏览器(客户端)发出请求时,有时会传递参数给视图函数,以实现补充请求信息的作用,这时就要在路由配置项中加上URL参数,这个参数会被对应的视图函数接收。

    """mysite URL Configuration
    
    The `urlpatterns` list routes URLs to views. For more information please see:
        https://docs.djangoproject.com/en/3.2/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 polls import views as views1
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('test/', views1.test),
        path('getinfo/', views1.getinfo),
        path('hello/<int:year>/<int:month>', views1.hello),
    
        # path(r'^test/', views1.test)
    ]
    
    import json
    
    from django.shortcuts import render
    from django.shortcuts import HttpResponse
    from django.shortcuts import HttpResponseRedirect
    
    # Create your views here.
    
    def test(request):
        # return HttpResponse("hello world!")
        return render(request,'test.html')
    
    def getinfo(request):
        data = request.POST.get('data')
        print(type(data))
        data = json.loads(data)
        print(data)
        print(type(data))
        id1 = data['id1']
        id2 = data['id2']
        id3 = int(id1)+int(id2)
        return HttpResponse(str(id3))
    
    def hello(request,year,month):
        #参数是int类型,转换为字符串
        year1 = str(year) + '年'
        month1 = str(month) + '月'
        data = {'year':year1,'month':month1}
        #通过render函数向前端页面传递变量year和month
        return render(request,'hello.html',data)
    
    
    hello.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>带参页面</title>
    </head>
    <body>
        <h2 align="center">带参URL页面</h2>
    <!--    传入的变量year和month,名字要和视图函数中render()传递的变量名一致-->
        <p align="center">URL传入参数:1是{{year}}, 2是{{month}}</p>
    </body>
    </html>

  • 相关阅读:
    Response 文件下载
    Tomcat Servlet
    Junit 反射 注解
    Stream流 方法引用
    函数式接口
    网络编程
    缓冲流、转换流、序列化流、打印流
    字节流 字符流
    File类 递归
    线程池 Lambda表达式
  • 原文地址:https://www.cnblogs.com/like1824/p/15437632.html
Copyright © 2011-2022 走看看