Django学习记录(2) 创建第一个app

之前已经创建完成了第一个project和app, 接下来说一下创建完成后该怎么做, 主要参考一下的是官方文档

project和app的区别

官方文档上是这样说的:

What’s the difference between a project and an app? An app is a Web application that does something – e.g., a Weblog system, a database of public records or a simple poll app. A project is a collection of configuration and apps for a particular website. A project can contain multiple apps. An app can be in multiple projects.

一个app是用来完成一些特定功能的, 比如一个博客系统, 一个简单的投票系统等等,而一个项目是一些应用的集合. 简单来说, 一个项目可以包含多个app, 一个app也是可以在多个项目中使用的

polls/views

接下来写第一个view函数, 在polls/views.py文件中:

from django.http import HttpResponse


def index(request):
    return HttpResponse("主页")

这是最简单的一个view视图函数了

polls/urls

使用startapp是没有urls.py这个文件的, 所以需要自己create一个,
然后这样写:

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index, name="index")
]

The next step is to point the root URLconf at the polls.urls module.

接下来要在mysite的urls.py中指向poll.urls

from django.conf.urls import url, include
from django.contrib import admin

urlpatterns = [
    url(r'^polls/', include('polls.urls')),
    url(r'^admin/', admin.site.urls),
]

incldue()函数允许引用其他的URLconfs, 但是注意使用include的时候, 正则表达式不要以$ 结束, 而是应该以/ 结束, 因为:

it chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLconf for further processing.

因为会将前面的匹配部分去掉, 将剩余的部分发送到include的URLconfs中

接下来运行一下, 在localhost:8000/polls就可以看见主页两个字了

When to use include()?

You should always use include() when you include other URL patterns. admin.site.urls is the only exception to this.

只要有其他的url patterns的时候, 就应该使用include, 除了admin.site.urls,
我使用版本和看的官方文档的版本都是1.11, 所以如果看到include(admin.site.urls)的情况, 是因为版本不同

深入url()方法

url()函数有两个必须的参数, regex和view, 还有两个参数, kwargs和name

url() argument: regex

显然, 这里是一个正则表达式, 这里是用来匹配url的

Django starts at the first regular expression and makes its way down the list, comparing the requested URL against each regular expression until it finds one that matches.

django会从第一个正则表达式开始, 一个个去匹配, 直到匹配到

Note that these regular expressions do not search GET and POST parameters, or the domain name.

注意这些正则表达式是不会匹配GET或者POST, 也不会匹配域名, 举个栗子:

https://www.example.com/myapp/ 的结果是myapp/, https://www.example.com/myapp?page=6 的结果也是myapp/

这些正则表达式在第一次加载URLconf模块的时候就被编译, 它们很快

url() argument: view

当正则表达式匹配到的时候, 就会调用指定的view函数

url() argument: kwargs

Arbitrary keyword arguments can be passed in a dictionary to the target view.

这个估计暂时不会用到

url() argument: name

Naming your URL lets you refer to it unambiguously from elsewhere in Django, especially from within templates. This powerful feature allows you to make global changes to the URL patterns of your project while only touching a single file.

命名url后可以在django其他地方引用

你可能感兴趣的:(Django学习记录(2) 创建第一个app)