Django官方文档笔记

来源:互联网 发布:杰科网络电视机顶盒gk 编辑:程序博客网 时间:2024/05/01 18:35

Django官方文档


Creating a project

$ django-admin startproject mysite

structure

$ tree.└── mysite    ├── manage.py    └── mysite        ├── __init__.py        ├── settings.py        ├── urls.py        └── wsgi.py
  1. The outer mysite/ root directory is just a container for your project.
  2. manage.py A command-line utility that lets you interact with this Django project in various ways.
  3. The inner mysite/ directory is the actual Python package for your project. Its name is the Python package name you’ll need to use to import anything inside it (e.g. mysite.urls).
  4. mysite/__init__.py: An empty file that tells Python that this directory should be considered a Python package.
  5. mysite/settings.py: Settings/configuration for this Django project.
  6. mysite/urls.py: The URL declaration for this Django project;
  7. mysite/wsgi.py: An entry-point for WSGI-compatible web servers to server your project.

The development server

$ python manage.py runserver , (Creating a local development server.)
Port 8000 by default, pass a port is allowed, as python manage.py runserver 8080

(learn_django) fengweilei@fengweilei-Inspiron-3521:~/django/mysite$ python3 manage.py runserverPerforming system checks...System check identified no issues (0 silenced).You have 14 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.Run 'python manage.py migrate' to apply them.December 21, 2017 - 12:16:21Django version 2.0, using settings 'mysite.settings'Starting development server at http://127.0.0.1:8000/Quit the server with CONTROL-C.[21/Dec/2017 12:16:56] "GET / HTTP/1.1" 200 16559[21/Dec/2017 12:16:56] "GET /static/admin/css/fonts.css HTTP/1.1" 200 423[21/Dec/2017 12:16:56] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 80304[21/Dec/2017 12:16:56] "GET /static/admin/fonts/Roboto-Bold-webfont.woff HTTP/1.1" 200 82564[21/Dec/2017 12:16:56] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 200 81348Not Found: /favicon.ico[21/Dec/2017 12:16:57] "GET /favicon.ico HTTP/1.1" 404 1972

这里写图片描述


Now that your environment – a “project” is set up, you can write your django application.

Projects VS apps
An app is a Web application that does something.
A project is a collection of configuration and apps for a particular website.
A project can contain mutiple apps.An app can be in multiple projects.
Your app can live anywhere on your Python path.

Creating the Pools app

$ python manage.py start pools

(learn_django) fengweilei@fengweilei-Inspiron-3521:~/django/mysite$ python3 manage.py startapp pools# we create our pool app right next to our manage.py file so that it can be imported as its own top-level module, rather than a submodule of mysite.
(learn_django) fengweilei@fengweilei-Inspiron-3521:~/django/mysite$ tree.├── db.sqlite3├── manage.py├── mysite│   ├── __init__.py│   ├── __pycache__│   │   ├── __init__.cpython-35.pyc│   │   ├── settings.cpython-35.pyc│   │   ├── urls.cpython-35.pyc│   │   └── wsgi.cpython-35.pyc│   ├── settings.py│   ├── urls.py│   └── wsgi.py└── pools    ├── admin.py    ├── apps.py    ├── __init__.py    ├── migrations    │   └── __init__.py    ├── models.py    ├── tests.py    └── views.py

Write your first view

Write these code in the views.py file:

from django.http import HttpResponsedef index(request):    return HttpResponse("Hello, world. You are at the pool index.")

Map the view to a URL

First , create a file called urls.py in the pools directory and write these code:

from django.cong.urls import urlfrom . import views  # .urlpatterns = [    url(r'^$', views.index, name='index'),]

Next, point the root URLconf at the pools.url module. (add the urlpatterns to mysite urlpatterns list.)

A URLconf maps URL patterns to views.
A URL pattern is simply the general form of a URL

mysite/url.py:

from django.contrib import adminfrom django.urls import path, includeurlpatterns = [    path('admin/', admin.site.urls),    path('pools/', include('pools.urls')),]

include() function allows referencing other URLconfs. When 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.
Since pools are in their own URLconf, they can be placed under “/pools/”, or “/fun_pools/”, or any other path root, and the app will still work.


以上,已经完成一个基本的web app了。

  1. python manage.py runserver 会创建本地服务器,处理客户端(浏览器)的请求。
  2. 浏览器中请求访问 http://127.0.0.1:8000/pools.
  3. 服务器根据URL映射,再Django代码中找到/pools 对应的处理函数——index()视图函数.
  4. index()返回一个HTTP响应,服务器把index()函数返回值变成一个真正的响应发送给浏览器。
  5. 浏览器看到一段话。

这里写图片描述

服务器中最后一行还记录了处理这次请求的信息。

  • 时间,格林尼治时间。东八区现在11:40。
  • GET /pools/, HTTP 请求方法为GET,获取 /pools/路由(对应的视图函数)。
  • HTTP/1.1, HTTP协议版本。
  • 200, HTTP状态码,处理成功。

Database setup

mysite/setting.py, it is a normal Python module with module-level variables representing Django settings.
We are using SQLite, don’t need to create anything beforehand – the datebase is just a file and created already.

INSTALLED_APPS include some apps by default (then we should add our pool app ):

  • django.contrib.admin : The admin site.
  • django.contrib.auth : An authentication system.
  • django.contrib.contenttypes : A framework for content types.
  • djando.contrib.sessions : A session framework.
  • django.contrib.messages : A message framework.
  • django.contrib.staticfiles : A framework for managing static files.

Some of these applications make use of at least one database table, we need to create the tables in the database before we can use them.
To do that, run the following command: $ python manage.py migrate

The migrate command looks at the INSTALLED_APPS setting and creates any necessary database tables.

(learn_django) fengweilei@fengweilei-inspiron-3521:~/django/mysite$ python3 manage.py migrateOperations to perform:  Apply all migrations: admin, auth, contenttypes, sessionsRunning migrations:  Applying contenttypes.0001_initial... OK  Applying auth.0001_initial... OK  Applying admin.0001_initial... OK  Applying admin.0002_logentry_remove_auto_add... OK  Applying contenttypes.0002_remove_content_type_name... OK  Applying auth.0002_alter_permission_name_max_length... OK  Applying auth.0003_alter_user_email_max_length... OK  Applying auth.0004_alter_user_username_opts... OK  Applying auth.0005_alter_user_last_login_null... OK  Applying auth.0006_require_contenttypes_0002... OK  Applying auth.0007_alter_validators_add_error_messages... OK  Applying auth.0008_alter_user_username_max_length... OK  Applying auth.0009_alter_user_last_name_max_length... OK  Applying sessions.0001_initial... OK(learn_django) fengweilei@fengweilei-inspiron-3521:~/django/mysite$ 

Creating Models

A model is the single, definitive source of truth above your data. It contains the essential fields and behaviors of the data you’re storing. Django follows the DRY Principle. The goal is to define your data model in one place and automatically derive thing from it.
This includes the migrations, migrations are entirely derived from your model file, and are essentially just a history that Django can rool through to update your database schema to match your current models.

In our pool app, we create two models:

pools/model.py

from django.db import models# Create your models here.class Question(models.Model):  # a table in the databse    question_text = models.CharField(max_length=200)   # a databse field in the model    pub_date = models.DateTimeField('data published') # pub_date is the name of tht fieldclass Choice(models.Model):    question = models.ForeignKey(Question, on_delete=models.CASCADE)    choice_text = models.CharField(max_length=200)  # CharField require you give it a max_length    vote = models.IntegerField(default=0)  # set the default value of votes to 0.# ForeignKey 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.

That small bit of model code give Django a lot of information. With it, Django is able to:

  • Create a database schema (CREATE TABLE statement) for this app.
  • Create a Python database-access API for accessing Question and Choice objects.

Then we need to add our pool app to the INSTALLED_APPS(the PoolConfig class is in the pools/app.py file.)

mysite/settings.py

INSTALLED_APPS = [    'pools.apps.PoolsConfig',    'django.contrib.admin',    'django.contrib.auth',    'django.contrib.contenttypes',    'django.contrib.sessions',    'django.contrib.messages',    'django.contrib.staticfiles',]

Now Django knows to include the pools app. Then run another command: $ python manage.py makemigrations pools

makemigrations tells Django that we’ve made some changes to our models and we’d like the changes to be stored as a migration.
Migrations are how Django stores changes to your models.(pools/migrations/0001_initial.py)

(learn_django) fengweilei@fengweilei-inspiron-3521:~/django/mysite$ python3 manage.py makemigrations poolsMigrations for 'pools':  pools/migrations/0001_initial.py    - Create model Choice    - Create model Question    - Add field question to choice

python manage.py sqlmigrate pools 0001 will show you what SQL that migration would run:

(learn_django) fengweilwi@fengweilei-inspiron-3521:~/django/mysite$ python3 manage.py sqlmigrate pools 0001BEGIN;---- Create model Choice--CREATE TABLE "pools_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "vote" integer NOT NULL);---- Create model Question--CREATE TABLE "pools_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "question_text" varchar(200) NOT NULL, "pub_date" datetime NOT NULL);---- Add field question to choice--ALTER TABLE "pools_choice" RENAME TO "pools_choice__old";CREATE TABLE "pools_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "vote" integer NOT NULL, "question_id" integer NOT NULL REFERENCES "pools_question" ("id") DEFERRABLE INITIALLY DEFERRED);INSERT INTO "pools_choice" ("id", "vote", "choice_text", "question_id") SELECT "id", "vote", "choice_text", NULL FROM "pools_choice__old";DROP TABLE "pools_choice__old";CREATE INDEX "pools_choice_question_id_ad7414eb" ON "pools_choice" ("question_id");COMMIT;

Now, we can run python manage.py migrate again to create those model tables in our database:

(learn_django) fengweilwi@fengweilei-inspiron-3521:~/django/mysite$ python3 manage.py migrateOperations to perform:  Apply all migrations: admin, auth, contenttypes, pools, sessionsRunning migrations:  Applying pools.0001_initial... OK

In summary, remember the three steps to make model changes:

  1. Change your models (in models.py)
  2. Run python manage.py makemigrations to create migrations for those changes
  3. Run python manage.py migrate to apply those changes to the database.

Playing with the API

Use the command python manage.py shell to invoke the Python shell and play around with the free API Django gives you.


Introducing the Django Admin

Django entirely automates creation of admin interfaces for models.
The admin is not intended to be used by site visitors, it is for site managers.

Creating an admin user

$ python manage.py createsuperuser

(learn_django) fengweilei@fengweilei-inspiron-3521:~/django/mysite$ python3 manage.py createsuperuserUsername (leave blank to use 'fengweilei'): fengweileiEmail address: 18790166674@163.comPassword: Password (again): Superuser created successfully.(learn_django) fengweilwi@fengweilei-inspiron-3521:~/django/mysite$ 

Start the development server

$ python manage.py runserver

(learn_django) fengweilwi@fengweilei-inspiron-3521:~/django/mysite$ python3 manage.py runserverPerforming system checks...System check identified no issues (0 silenced).December 23, 2017 - 14:26:27Django version 2.0, using settings 'mysite.settings'Starting development server at http://127.0.0.1:8000/Quit the server with CONTROL-C.[23/Dec/2017 14:27:13] "GET /admin HTTP/1.1" 301 0[23/Dec/2017 14:27:13] "GET /admin/ HTTP/1.1" 302 0[23/Dec/2017 14:27:13] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 1855[23/Dec/2017 14:27:13] "GET /static/admin/css/base.css HTTP/1.1" 200 16106[23/Dec/2017 14:27:13] "GET /static/admin/css/login.css HTTP/1.1" 200 1203[23/Dec/2017 14:27:13] "GET /static/admin/css/responsive.css HTTP/1.1" 200 17894[23/Dec/2017 14:27:13] "GET /static/admin/css/fonts.css HTTP/1.1" 304 0[23/Dec/2017 14:27:13] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 304 0[23/Dec/2017 14:27:13] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 304 0Not Found: /favicon.ico[23/Dec/2017 14:27:13] "GET /favicon.ico HTTP/1.1" 404 2078[23/Dec/2017 14:29:35] "POST /admin/login/?next=/admin/ HTTP/1.1" 302 0[23/Dec/2017 14:29:35] "GET /admin/ HTTP/1.1" 200 2989[23/Dec/2017 14:29:35] "GET /static/admin/css/dashboard.css HTTP/1.1" 200 412[23/Dec/2017 14:29:35] "GET /static/admin/img/icon-addlink.svg HTTP/1.1" 200 331[23/Dec/2017 14:29:35] "GET /static/admin/img/icon-changelink.svg HTTP/1.1" 200 380[23/Dec/2017 14:29:35] "GET /static/admin/fonts/Roboto-Bold-webfont.woff HTTP/1.1" 304 0

这里写图片描述

这里写图片描述

The groups and users are provided by django.contrib.auth (INSTALLED_APPS), the authentication framework shipped by Django.


Make the pool app modifiable in the admin

Our pool app is not displayed on the admin index page.
We need to tell the admin that Question objects have an admin interface.

pools/admin.py

from django.contrib import adminfrom .models import Question# Register your models here.admin.site.register(Question)

这里写图片描述

这里写图片描述

这里写图片描述


Views

A view is a “type” of Web page in our Django application that generally serves a specific function and has a specific template.
In Django, web pages and other content are delivered by views. Each view is represented by a simple Python function. Django will choose a view by examining the URL that’s requested (URL pattern, the part of URL after the domain name).
To get from a URL to a view, Django uses ‘URLconfs’, a URLconf maps URL patterns to views.

First, add some views (without using templates):

pools/views.py:

from django.shortcuts import render# Create your views here.from django.http import HttpResponsedef index(request):    return HttpResponse("Hello, world. You are at the pool index.")def detail(request, question_id):    return HttpResponse("You're looking at question %s." % question_id)def results(request, question_id):    response = "You're looking at the results of question %s"    return HttpResponse(response % question_id)def vote(request, question_id):    return HttpResponse("You're voting on question %s" % question_id)

Then, complete the URLconfs:

pools/urls.py:

from django.urls import pathfrom . import views  # .urlpatterns = [    path('', views.index, name='index'),    path('<int:question_id>/', views.detail, name='detail'),    path('<int:question_id>/results/', views.results, name='results'),    path('<int:question_id>/vote/', views.vote, name='vote'),]

现在,在浏览器中能通过URL中提供的参数信息,动态生成一个网页:

这里写图片描述

这里写图片描述

这里写图片描述


Templates

简单的响应还好,如果网页信息太多,全都挤在Python代码中,太难看了。( 模板)

Use Django’s template system to separate the design from Python by creating a template that the view can use.

  • First, create a directory called templates in the pools directory, Django will look for templates in there.
  • Within the templates directory, create another directory pools,ensure Django can find the right template, say, namespacing the template.(DjangoTemplates looks for a “templates” in each of the INSTALLED_APPS)

Write some code in the pools/templates/pools/index.html:

{% if latest_question_list %}  <ul>  {% for question in latest_question_list %}    <li><a href="/pools/{{ question.id }}/">{{ question.question_text }}</a></li>  {% endfor %}  </ul>{% else %}  <p>No pools are avaiable.</p>{% endif %}

Instead of HttpResponse, we use the render() shortcut.
The render() function takes some arguments and returns an HttpResponse object of the given template rendered with the given context.

pools/views.py

from django.shortcuts import renderfrom .models import Question# Create your views here.#from django.http import HttpResponsedef index(request):    latest_question_list = Question.objects.order_by('-pub_date')[:5]    context = {'latest_question_list':latest_question_list}    return render(request, 'pools/index.html', context)

这里写图片描述


Introducing automated testing

Tests are simple routines that check the operation of your code.

Why you need to create tests
Tests will save you time
Tests don’t just identify problems, they prevent them
Tests make your code more attractive
Tests help teams work together

大概看完了文档,写具体项目的时候再查文档。

未完待续


晚上突然想翻一下Django官方文档,真的好详细,直接按照这个学多好。
断断续续学Python快一年了,想在工作中继续学习,无奈找不到一份实习的工作。
可能是快过年了。
更多的是出身不好,不是计算机相关专业,本科学校也不是985、211。照着教程敲两行代码的水平。如果我是负责人,可能也不倾向于招这样的员工。
最近,这些知识点越来越亲切,所有的知识开始融汇贯通起来。只是,快吃不上饭了,也渐渐没有了刚开始学习时的动力了。
就算有份实习的工作,也要开始考虑发展前景了。
还转行干什么?
要好好找份洗碗搬砖的工作,攒些钱,明年考研。
后天就是今年的考研了。
年初,看到好多大佬说IT行业只看中手艺,不看重学历,一头扎了进来。
也不太后悔浪费了半年的时间。
至少自己尝试一下,不能直接依靠别人的经验建议来生活呀。

2017/12/21


今天就是今年的考研了,希望考研的小伙伴顺利考完。
白天出去转了一圈,晚上回来接着学习了一会儿。
感觉不应该太着急,美好的东西,即使迟到,也依旧美好。

2017/12/23

原创粉丝点击