django中urls和views的基本用法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_25545645/article/details/77123797

django中urls的用法

  1. url格式

    URL解释:

    schema://host[:port#]/path/.../[?query-string][#anchor]

    schema:指定使用的协议(例如:http,https, ftp)

    host:Http服务器的IP地址或者域名

    port:端口号,http默认是80端口

    path:访问资源的路径

    query-string:发送给http服务器的数据

    anchor:锚点

  2. 例子

    注意:末尾的/是必须的,虽然浏览器会根据情况帮助自动添加/,但是不要以为不输入就等于不添加。

    from django.conf.urls import url
      from django.contrib import admin
      from hello import views
    
      urlpatterns = [
          url(r'^admin/', admin.site.urls),
          url(r'^hello/$',views.hello),
    	url(r'^books/$',views.books,name=“books”),
    ]
  3. url函数的定义

    Def url(regex, view, kwargs=None, name=None)

    Regex: 传入的url要匹配的正则表达式

    View:一个可调用的对象或一个url类型的列表或元组

    Kwargs:关键字参数,必须是一个字典数组,可以通过这个参数传递更多的信息给view

    Name:关键字参数,是一个字符串,用于给regex匹配的字符串取名字

  4. url常用正则表达式

    模式匹配示例:
    url(r‘books/python/$', views.books_python) 
     # books/python
    url(r‘books/php/$', views.books_php) 
     # books/php
    url(r‘books/([a-zA-Z0-9]*)/$', views.books)
    url(r‘books/([\S\s]*)/$', views.books)
    
    参数传递示例:
    url(r‘books/\d{2}/$', views.books) 
     # books/66
    url(r‘books/(?P<id>\d{2})/$', views.books)
    #books/10   books(req,id=10)
    url(r‘books/(?P<id>\d{2})/(?P<ver>\w+) /$', views.books)
    #test/20/3   books(req,id=20,ver=3)

views的配置

访问:http://192.168.10.107:8000/hello/pytho111/

urls.py

url(r'hello/([\S\s]*)/$', views.hello_books),

  1. HttpResponse

    #views.py
    from django.template import Template,Context
    def hello_books(request, bn):
    #step1 生成模板对象
      t = Template(u'<h1><body>欢迎浏览{{books_name}}</body></h1>')
    #step2 生成上下文对象
      c = Context({'books_name':bn})
    #step3 渲染
      html = t.render(c)
    #step4 回应
      return HttpResponse(html)
  2. get_template

    [root@erhui1 hellodjango]# cat templates/hello_books.html 
    <html>
    <body>
    <h1>
    欢迎访问{{books_name}}
    </h1>
    </body>
    </html>
    
    #views.py
    from django.template.loader import get_template
    def hello_books(request, bn):
      t = get_template('hello_books.html')
      html = t.render({"books_name":bn})
      return HttpResponse(html)
  3. render_to_reponse

    from django.shortcuts import render,render_to_response
    def hello_books(request, bn):
      return render_to_response('hello_books.html',{"books_name":bn})
  4. render

    def hello_books(request, bn):
      return render(request,'hello_books.html',{"books_name":bn})

展开阅读全文

没有更多推荐了,返回首页