django-1.11英文文档笔记(一)

1、urls匹配

### urls.py

urlpatterns = [
url(r'^articles/([0-9]{4})/$', views.year_archive),
url(r'^articles/([0-9]{4})/([0-9]{2})/$', views.month_archive),
url(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$', views.article_detail),
]

The code above maps URLs, as simple regular expressions, to the location of Python callback functions (“views”).
The regular expressions use parenthesis to “capture” values from the URLs. When a user requests a page, Django runs
through each pattern, in order, and stops at the first one that matches the requested URL. (If none of them matches,
Django calls a special-case 404 view.) This is blazingly fast, because the regular expressions are compiled at load
time.
Once one of the regexes matches, Django calls the given view, which is a Python function. Each view gets passed a
request object – which contains request metadata – and the values captured in the regex.
For example, if a user requested the URL “/articles/2005/05/39323/”, Django would call the function news.views.
article_detail(request, ‘2005’, ‘05’, ‘39323’).

  • 使用括号()去获取参数。
  • url按顺序匹配,一旦匹配成功即结束,当全部不匹配就报404错误。
  • 正则表达式在项目加载时就已经编译,所以后面的匹配飞快。
  • 匹配成功就会调用views.py中对应的python函数,并会传递个request object参数,包含request元数据和url正则匹配到的数据。

Note that these regular expressions do not search GET and POST parameters, or the domain name. For example,
in a request to https://www.example.com/myapp/, the URLconf will look for myapp/. In a request to
https://www.example.com/myapp/?page=3, the URLconf will also look for myapp/.

  • url正则匹配时,不匹配 GET 和 POST 的参数,也不匹配域名。只匹配域名与参数之间的那部分。

2、templates模板

### base.html

{% load static %}
<html>
<head>
<title>{% block title %}{% endblock %}</title>
</head>
........

### year_archive.html

{% extends "base.html" %}
{% block title %}Articles for {{ year }}{% endblock %}
...........

Finally, Django uses the concept of “template inheritance”. That’s what the {% extends “base.html” %}
does. It means “First load the template called ‘base’, which has defined a bunch of blocks, and fill the blocks with
the following blocks.” In short, that lets you dramatically cut down on redundancy in templates: each template has to
define only what’s unique to that template.
It also lets you create multiple versions of a site, with different base templates, while reusing child templates. Django’s
creators have used this technique to create strikingly different mobile versions of sites – simply by creating a new base
template.

  • django templates有个强大的功能:模板继承,可以定义一个base.html,然后在其它 html 中使用 extends 语法继承 base.html 的结构与内容,并填充定义的参数。

3、django卸载

If you are upgrading your installation of Django from a previous version, you will need to uninstall the old Django
version before installing the new version.
If you installed Django using pip or easy_install previously, installing with pip or easy_install again will
automatically take care of the old version, so you don’t need to do it yourself.
If you previously installed Django using python setup.py install, uninstalling is as simple as deleting the
django directory from your Python site-packages. To find the directory you need to remove, you can run the
following at your shell prompt (not the interactive Python prompt):

python -c "import django; print(django.__path__)"
  • 当你准备升级django时,你需要先把旧版本的django卸载。
  • 如果你旧版本是使用pip方式安装,那可以直接使用pip方式升级,无需考虑其它,系统会自动帮助你管理。
  • 如果你是使用 python setup.py install 方式安装,那需要找到旧版本的安装目录并把它删除,安装目录是在 site-packages 下,可以使用以下命令定位到django的安装目录:
    python -c “import django; print(django.path)”

4、django 中 project 与 app的区别

What’s the difference between a project and an app? An app is aWeb 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.
Your apps can live anywhere on your Python path. In this tutorial, we’ll create our poll app right next to your manage.
py file so that it can be imported as its own top-level module, rather than a submodule of mysite.

  • 一个app可以看成一个功能模块。
  • 一个project可以包含多个app,一个app也可以同时属于多个project。
  • project 与 app 是多对多关系。
  • 虽然app可以在任意路径,但使用中肯定是放在project的根目录下,方便管理,也方便import。

5、urls include() 函数功能

### mysite/urls.py ### mysyte is project name

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

### polls/urls.py ### polls is app name

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

The include() function allows referencing other URLconfs. Note that the regular expressions for the include()
function doesn’t have a $ (end-of-string match character) but rather a trailing slash. Whenever Django encounters
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.
The idea behind include() is to make it easy to plug-and-play URLs. Since polls are in their own URLconf
(polls/urls.py), they can be placed under “/polls/”, or under “/fun_polls/”, or under “/content/polls/”, or any
other path root, and the app will still work.

  • include()函数功能是为了引入别的模块的 urlconf 文件。
  • 当 url 匹配遇到 include,它会把第一次匹配到内容去除,然后把剩下的那部分string 传入给 include 所包含的 urlconf 去继续匹配。

The url() function is passed four arguments, two required: regex and view, and two optional: kwargs, and
name. At this point, it’s worth reviewing what these arguments are for.

  • url()函数有四个参数,两个必需的:url正则表达式 、view,两个非必要: kwargs 、name。

6、数据库model映射

### polls/models.py

 from django.db import models
 class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

Finally, note a relationship is defined, using ForeignKey. That tells Django each Choice is related to a single
Question. Django supports all the common database relationships: many-to-one, many-to-many, and one-to-one.

  • 用关键字 Foreignkey 表示外键关系。

By running makemigrations, you’re telling Django that you’ve made some changes to your models (in this case, you’ve made new ones) and that you’d like the changes to be stored as a migration.
Migrations are how Django stores changes to your models (and thus your database schema) - they’re just files on disk. You can read the migration for your new model if you like; it’s the file polls/migrations/0001_initial.py. Don’t worry, you’re not expected to read them every time Django makes one, but they’re designed to be human-editable in case you want to manually tweak how Django changes things.

  • makemigrations命令,会通知django 相应的models有变化,再使用migrate命令把改变映射到数据库表。

Table names are automatically generated by combining the name of the app (polls) and the lowercase name of the model – question and choice. (You can override this behavior.)
Primary keys (IDs) are added automatically. (You can override this, too.)

  • 数据库表名会自动生成,规则为:appname_modelname。
  • 每个表都会自动生成主键。

10、django开发过程中的命令

django-admin startproject mysite   ##创建django project
python manage.py startapp polls    ##创建django app
python manage.py runserver 8000    ##启动django project自带的 web server
python manage.py migrate           ##自动创建数据库表
python manage.py makemigrations polls  ##通知django polls modle有变化
python manage.py sqlmigrate polls 0001  ##查询对应要执行的sql语句
python manage.py createsuperuser  ##创建admin后管的超级用户
http://127.0.0.1:8000/admin/      ##后管网址
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值