The second framework Django Django The second framework

First, the knowledge review

1, MTV model

  model: model, and database-related

  template: template, store html files, templates, syntax (the purpose of the variable how cleverly embedded into HTML pages).

  views: view function

Plus urls: mapping between the path and the url ,, view function can not one to one.

2, the relevant commands

  Create a Django project: django-admin startproject projectname

  Create applications in a project: python3 manage.py startapp appname

  Run: python3 manage.py runserver IP PORT

3, url configuration (URLconf) urls.py

  Function: url mapping relationship established with the view function

  url (regex (rules), the view function, [optional])

   url:http://127.0.0.1:8080/blog/articles/2003/05?a=1&b=2

     Match string: url user input corresponding path / blog / articles / 2003/05

 note:

  (1) covers the case of the emergence of the phenomenon, that is, matching rules conflict, the first match url

  (2) unknown packet: url (r '^ articles / (\ d {4}) / (\ d {2}) $', views.year_month), # year (requset, 1990,12) according to the position-parameters

  (3) known packet: URL (R & lt 'Articles ^ / ( ? P <year> ? \. 4 {D}) / (P <month The> \ D {2}) $', views.year_month), # year (requset , year = 1990, month = 12 ) by the position-parameters

  (4)url分发:url(r'^blog/',include('blog.urls'))

SUPPLEMENTARY view function

1, a view function: it must be to include two objects (source inside the render HttpResponse object)

       The request object: ----- "All the information requests

       HttpResponse: ----- "content of the response (String)

2, get a request to send data: http: //127.0.0.1: 8000 / login.html user = asd & pwd = asd?

  Key: Which contains data request
    . 1, : `` request.GET`` data GET request, if no data is an empty dictionary} {
    2, of request.POST: data POST request, if no data is an empty dictionary} {
    . 3, request .method the gET or POST:: request embodiment
    4, when a key request to the plurality of values: request.POST.getlist ( "Hobby")   . 5, request.path : request path (path will get, get no data)    
           

          Request URL: HTTP: //127.0.0.1: 8000 / index.html / 23 is A. 1 =?
          Path: request.path: /index.html/23
              . 6,   request.get_full_path ()  : request path (data path and would take to)
         the request url: HTTP: //127.0.0.1: 8000 / index.html / 23 A = 1?
         request.get_full_path ():? / index.html / 23 A = 1

  

Third, the difference between the render function and redirect functions

render: only return to the page content, but does not send a second request

redirect: play the second request, url update

Concrete examples

render:

redirect:

 Fourth, reverse analysis

In use Django project, a common requirement is to get the final form of the URL for the embedded into the generated content (and views displayed to a user's URL, etc.) or for navigation processing server (redirection).

There is a strong wish not to hard-code the URL (laborious, error-prone and not expandable) or design a special URL generation mechanism URLconf irrelevant, because it is easy to lead to a certain extent URL expired.

In other words, what is needed is a mechanism DRY. Among other a little, it also allows for the design of the URL can be automatically updated without having to traverse the source code for the project to search for and replace outdated URL.

Type (positional parameters, keyword parameters) and other information necessary to obtain the value of a URL beginning think the information is processed identification (such as name) its view, have to find the correct URL parameters of view.

Django provides a way is to let the URL mapping URL design is the only place. You fill your URLconf, then use it in both directions:

  • According URL request user / browser launched, it calls the correct Django view, and extract the value of its required parameters from the URL.
  • 根据Django 视图的标识和将要传递给它的参数的值,获取与之关联的URL。

第一种方式是我们在前面的章节中一直讨论的用法。第二种方式叫做反向解析URL、反向URL 匹配、反向URL 查询或者简单的URL 反查。

在需要URL 的地方,对于不同层级,Django 提供不同的工具用于URL 反查:

  • 在模板中:使用url 模板标签。
  • 在Python 代码中:使用django.core.urlresolvers.reverse() 函数。
  • 在更高层的与处理Django 模型实例相关的代码中:使用get_absolute_url() 方法。

例子:

考虑下面的URLconf:

复制代码
复制代码
from django.conf.urls import url

from . import views

urlpatterns = [
    #...
    url(r'^articles/([0-9]{4})/$', views.year_archive, name='news-year-archive'),
    #...
]
复制代码
复制代码

根据这里的设计,某一年nnnn对应的归档的URL是/articles/nnnn/

你可以在模板的代码中使用下面的方法获得它们:

复制代码
复制代码
<a href="{% url 'news-year-archive' 2012 %}">2012 Archive</a>

<ul>
{% for yearvar in year_list %}
<li><a href="{% url 'news-year-archive' yearvar %}">{{ yearvar }} Archive</a></li>
{% endfor %}
</ul>
复制代码
复制代码

在Python 代码中,这样使用:

复制代码
复制代码
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect

def redirect_to_year(request):
    # ...
    year = 2006
    # ...
    return HttpResponseRedirect(reverse('news-year-archive', args=(year,)))
复制代码
复制代码

如果出于某种原因决定按年归档文章发布的URL应该调整一下,那么你将只需要修改URLconf 中的内容。

在某些场景中,一个视图是通用的,所以在URL 和视图之间存在多对一的关系。对于这些情况,当反查URL 时,只有视图的名字还不够。

 

例子中:

分析:想我们一开始写的硬编码,也就是吧action要跳转的路径写死了。但是像淘宝,天猫等都会经常更新新东西,,那么你的页面上的url路径也会时不时的变化。但是如果有特别多的商品,那么你就得去服务端一个一个的改,这样显得很麻烦,那么有没有一种机制帮我们解决问题呢?那就按照我下面的办法解决。就把url路径写活了。

1、首先给url起一个别名。

2、然后在login.html中写上{%  url ‘别名’’  %}    ,如果在页面中点击查看元素,它会变成login.html,,,当然我的是分发了,,就会变成test/login.html

3、这样你就可以修改你的正则了,,因为他是按照别名走的,不会影响。

urls.py

login.html

查看元素的结果:

 

 这样的好处是:无论你怎么改你要匹配的url,只要你写上了别名。在html实现了模板语法,就会去找别名对应的那个url,以后不管你怎么改url都没事,就写活了,就不像一开始写的硬编码了。

 

一、知识点回顾

1、MTV模型

  model:模型,和数据库相关的

  template:模板,存放html文件,模板语法(目的是将变量如何巧妙的嵌入到HTML页面中)。

  views:视图函数

另加urls:url路径与视图函数的映射关系,,可以不是一一对应的。

2、相关的一些命令

  创建一个Django项目:django-admin  startproject  projectname

  创建一个项目下的应用:python3  manage.py  startapp  appname

  运行:python3  manage.py  runserver  IP PORT

3、url配置(URLconf)urls.py

  功能:建立起url与视图函数的映射关系

  url(正则表达式(规则),视图函数,[可选参数])

   url:http://127.0.0.1:8080/blog/articles/2003/05?a=1&b=2

     匹配字符串:用户输入的url对应的路径    /blog/articles/2003/05

 注意:

  (1)出现覆盖现象的情况,也就是匹配规则冲突的时候,匹配第一个url

  (2)无名分组:url(r'^articles/(\d{4})/(\d{2})$', views.year_month),  # year(requset,1990,12)   按位置传参数

  (3)有名分组:url(r'^articles/(?P<year>\d{4})/(?P<month>\d{2})$', views.year_month),  # year(requset,year=1990,month=12)   按位置传参数

  (4)url分发:url(r'^blog/',include('blog.urls'))

二、视图函数的补充

1、视图函数:一定是要包含两个对象的(render源码里面有HttpResponse对象)

       request对象:-----》所有的请求信息

       HttpResponse:-----》响应的内容(字符串)

2、get请求发送数据:http://127.0.0.1:8000/login.html?user=asd&pwd=asd

  重点:request里包含哪些数据
    1、request.GET: GET请求的数据,如果没有数据是一个空字典    {}
    2、request.POST:POST请求的数据 ,如果没有数据是一个空字典  {}
    3、request.method:请求方式:GET 或 POST
    4、请求某个键下多个值时:request.POST.getlist("hobby")
              5、 request.path : 请求路径(只会拿到路径,不拿数据)    

          请求url:http://127.0.0.1:8000/index.html/23?a=1
          path:request.path:/index.html/23
              6、  request.get_full_path()  :请求路径(路径和数据都会拿到)
         请求url:http://127.0.0.1:8000/index.html/23?a=1
         request.get_full_path():/index.html/23?a=1

  

三、render函数和redirect函数的区别

render:只会返回页面内容,但是未发送第二次请求

redirect:发挥了第二次请求,url更新

具体实例说明

render:

redirect:

 四、反向解析

在使用Django 项目时,一个常见的需求是获得URL 的最终形式,以用于嵌入到生成的内容中(视图中和显示给用户的URL等)或者用于处理服务器端的导航(重定向等)。

人们强烈希望不要硬编码这些URL(费力、不可扩展且容易产生错误)或者设计一种与URLconf 毫不相关的专门的URL 生成机制,因为这样容易导致一定程度上产生过期的URL。

换句话讲,需要的是一个DRY 机制。除了其它有点,它还允许设计的URL 可以自动更新而不用遍历项目的源代码来搜索并替换过期的URL。

获取一个URL 最开始想到的信息是处理它视图的标识(例如名字),查找正确的URL 的其它必要的信息有视图参数的类型(位置参数、关键字参数)和值。

Django 提供一个办法是让URL 映射是URL 设计唯一的地方。你填充你的URLconf,然后可以双向使用它:

  • 根据用户/浏览器发起的URL 请求,它调用正确的Django 视图,并从URL 中提取它的参数需要的值。
  • 根据Django 视图的标识和将要传递给它的参数的值,获取与之关联的URL。

第一种方式是我们在前面的章节中一直讨论的用法。第二种方式叫做反向解析URL、反向URL 匹配、反向URL 查询或者简单的URL 反查。

在需要URL 的地方,对于不同层级,Django 提供不同的工具用于URL 反查:

  • 在模板中:使用url 模板标签。
  • 在Python 代码中:使用django.core.urlresolvers.reverse() 函数。
  • 在更高层的与处理Django 模型实例相关的代码中:使用get_absolute_url() 方法。

例子:

考虑下面的URLconf:

复制代码
复制代码
from django.conf.urls import url

from . import views

urlpatterns = [
    #...
    url(r'^articles/([0-9]{4})/$', views.year_archive, name='news-year-archive'),
    #...
]
复制代码
复制代码

根据这里的设计,某一年nnnn对应的归档的URL是/articles/nnnn/

你可以在模板的代码中使用下面的方法获得它们:

复制代码
复制代码
<a href="{% url 'news-year-archive' 2012 %}">2012 Archive</a>

<ul>
{% for yearvar in year_list %}
<li><a href="{% url 'news-year-archive' yearvar %}">{{ yearvar }} Archive</a></li>
{% endfor %}
</ul>
复制代码
复制代码

在Python 代码中,这样使用:

复制代码
复制代码
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect

def redirect_to_year(request):
    # ...
    year = 2006
    # ...
    return HttpResponseRedirect(reverse('news-year-archive', args=(year,)))
复制代码
复制代码

如果出于某种原因决定按年归档文章发布的URL应该调整一下,那么你将只需要修改URLconf 中的内容。

在某些场景中,一个视图是通用的,所以在URL 和视图之间存在多对一的关系。对于这些情况,当反查URL 时,只有视图的名字还不够。

 

例子中:

分析:想我们一开始写的硬编码,也就是吧action要跳转的路径写死了。但是像淘宝,天猫等都会经常更新新东西,,那么你的页面上的url路径也会时不时的变化。但是如果有特别多的商品,那么你就得去服务端一个一个的改,这样显得很麻烦,那么有没有一种机制帮我们解决问题呢?那就按照我下面的办法解决。就把url路径写活了。

1、首先给url起一个别名。

2、然后在login.html中写上{%  url ‘别名’’  %}    ,如果在页面中点击查看元素,它会变成login.html,,,当然我的是分发了,,就会变成test/login.html

3、这样你就可以修改你的正则了,,因为他是按照别名走的,不会影响。

urls.py

login.html

查看元素的结果:

 

 这样的好处是:无论你怎么改你要匹配的url,只要你写上了别名。在html实现了模板语法,就会去找别名对应的那个url,以后不管你怎么改url都没事,就写活了,就不像一开始写的硬编码了。

 

Guess you like

Origin www.cnblogs.com/maaosheng/p/11621542.html