Django学习笔记1

18 篇文章 0 订阅
3 篇文章 0 订阅

1. django在1.4以后,工程布局上做了改动。项目里不是4个文件了,而是一个manage.py文件,和一个文件夹(包含__init__.py ,setting.py , urls.py,wsgi.py)。如下:

2.  django开发服务是可用在开发期间的,一个内建的,轻量的web服务。 我们提供这个服务器是为了让你快速开发站点,也就是说在准备发布产品之前,无需进行产品级 Web 服务器(比如 Apache)的配置工作。 开发服务器监测你的代码并自动加载它,这样你会很容易修改代码而不用重启动服务。

如果你还没启动服务器的话,请切换到你的项目目录里 (cd mysite ),运行下面的命令:

python manage.py runserver

默认情况下, runserver 命令在 8000 端口启动开发服务器,且仅监听本地连接。 要想要更改服务器端口的话,可将端口作为命令行参数传入:

python manage.py runserver 8080

通过指定一个 IP 地址,你可以告诉服务器–允许非本地连接访问。 如果你想和其他开发人员共享同一开发站点的话,该功能特别有用。 `` 0.0.0.0`` 这个 IP 地址,告诉服务器去侦听任意的网络接口。

python manage.py runserver 0.0.0.0:8000

完成这些设置后,你本地网络中的其它计算机就可以在浏览器中访问你的 IP 地址了。比如:http://192.168.1.103:8000/ .

3. Django 1.8版本里urls.py文件中urlpatterns生成方式有了简化,

老版本调用patterns函数:

from django.conf.urls import include, url,patterns
from django.contrib import admin
from mysite.views import hello,current_datetime

urlpatterns = patterns(
    url(r'^admin/', include(admin.site.urls)),
    url('^hello/$',hello),
    url('^time/$',current_datetime),
    )
1.8版本里:
from django.conf.urls import include, url
from django.contrib import admin
from mysite.views import hello,current_datetime

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url('^hello/$',hello),
    url('^time/$',current_datetime),
    ]

4. 总结一下,Django最简单的运行流程:

  1. 进来的请求转入/hello/.

  1. Django通过在ROOT_URLCONF配置来决定根URLconf.

  1. Django在URLconf中的所有URL模式中,查找第一个匹配/hello/的条目。

  1. 如果找到匹配,将调用相应的视图函数

  1. 视图函数返回一个HttpResponse

  1. Django转换HttpResponse为一个适合的HTTP response, 以Web page显示出来

5.从URL里获取参数的方法

urlpatterns = patterns('',
    (r'^hello/$', hello),
    (r'^time/$', current_datetime),
    (r'^time/plus/(\d{1,2})/$', hours_ahead),
)

from django.http import Http404, HttpResponse
import datetime

def hours_ahead(request, offset):
    try:
        offset = int(offset)
    except ValueError:
        raise Http404()
    dt = datetime.datetime.now() + datetime.timedelta(hours=offset)
    html = "<html><body>In %s hour(s), it will be %s.</body></html>" % (offset, dt)
    return HttpResponse(html)

offset 是从匹配的URL里提取出来的。 例如:如果请求URL是/time/plus/3/,那么offset将会是3;如果请求URL是/time/plus/21/,那么offset将会是21。请注意:捕获值永远都是字符串(string)类型,而不会是整数(integer)类型,即使这个字符串全由数字构成(如:“21”)。

20


(从技术上来说,捕获值总是Unicode objects,而不是简单的Python字节串,但目前不需要担心这些差别。)

6.Python 的“真值”

在Python和Django模板系统中,以下这些对象相当于布尔值的False

  • 空列表([] )

  • 空元组(() )

  • 空字典({} )

  • 空字符串('' )

  • 零值(0 )

  • 特殊对象None

  • 对象False(很明显)

  • 提示:你也可以在自定义的对象里定义他们的布尔值属性(这个是python的高级用法)。

    1

除以上几点以外的所有东西都视为`` True``

7.模板

模板系统基本知识
2

模板是一个文本,用于分离文档的表现形式和内容。 模板定义了占位符以及各种用于规范文档该如何显示的各部分基本逻辑(模板标签)。 模板通常用于产生HTML,但是Django的模板也能产生任何基于文本格式的文档。

用两个大括号括起来的文字(例如 {{ person_name }} )称为 变量(variable) 。这意味着在此处插入指定变量的值

在Python代码中使用Django模板的最基本方式如下:

3

  1. 可以用原始的模板代码字符串创建一个 Template 对象, Django同样支持用指定模板文件路径的方式来创建Template 对象;

  1. 调用模板对象的render方法,并且传入一套变量context。它将返回一个基于模板的展现字符串,模板中的变量和标签会被context值替换。

你一定好奇,为什么我们运行python manage.py shell而不是python。这两个命令都会启动交互解释器,但是manage.py shell命令有一个重要的不同: 在启动解释器之前,它告诉Django使用哪个设置文件。 Django框架的大部分子系统,包括模板系统,都依赖于配置文件;如果Django不知道使用哪个配置文件,这些系统将不能工作。

1

如果你想知道,这里将向你解释它背后是如何工作的。 Django搜索DJANGO_SETTINGS_MODULE环境变量,它被设置在settings.py中。例如,假设mysite在你的Python搜索路径中,那么DJANGO_SETTINGS_MODULE应该被设置为:’mysite.settings’。

14

当你运行命令:python manage.py shell,它将自动帮你处理DJANGO_SETTINGS_MODULE。 在当前的这些示例中,我们鼓励你使用`` python manage.py shell``这个方法,这样可以免去你大费周章地去配置那些你不熟悉的环境变量。

随着你越来越熟悉Django,你可能会偏向于废弃使用`` manage.py shell`` ,而是在你的配置文件.bash_profile中手动添加 DJANGO_SETTINGS_MODULE这个环境变量。

7.1 变量

句点查找规则可概括为: 当模板系统在变量名中遇到点时,按照以下顺序尝试进行查找:

  • 字典类型查找 (比如 foo["bar"] )

    5

  • 属性查找 (比如 foo.bar )

  • 方法调用 (比如 foo.bar() )

  • 列表类型索引查找 (比如 foo[bar] )

系统使用找到的第一个有效类型。 这是一种短路逻辑。

句点查找可以多级深度嵌套。 例如在下面这个例子中 {{person.name.upper}} 会转换成字典类型查找(person['name'] ) 然后是方法调用( upper() ):

>>> from django.template import Template, Context
>>> person = {'name': 'Sally', 'age': '43'}
>>> t = Template('{{ person.name.upper }} is {{ person.age }} years old.')
>>> c = Context({'person': person})
>>> t.render(c)
u'SALLY is 43 years old.'

7.2.标签

if

{% if %} 标签不允许在同一个标签中同时使用 and 和 or ,因为逻辑上可能模糊的,例如,如下示例是错误的: 比如这样的代码是不合法的:

{% if athlete_list and coach_list or cheerleader_list %}

系统不支持用圆括号来组合比较操作。



只有模板变量,字符串,整数和小数可以作为 {% ifequal %} 标签的参数。下面是合法参数的例子:

{% ifequal variable 1 %}
{% ifequal variable 1.23 %}
{% ifequal variable 'foo' %}
{% ifequal variable "foo" %}
for
5

{% for %} 允许我们在一个序列上迭代。

给标签增加一个 reversed 使得该列表被反向迭代:

{% for athlete in athlete_list reversed %}
...
{% endfor %}

所以`` for`` 标签支持一个可选的`` {% empty %}`` 分句,通过它我们可以定义当列表为空时的输出内容 下面的例子与之前那个等价:

17

{% for athlete in athlete_list %}
    <p>{{ athlete.name }}</p>
{% empty %}
    <p>There are no athletes. Only computer programmers.</p>
{% endfor %}

Django不支持退出循环操作。 如果我们想退出循环,可以改变正在迭代的变量,让其仅仅包含需要迭代的项目。 同理,Django也不支持continue语句,我们无法让当前迭代操作跳回到循环头部。 (请参看本章稍后的理念和限制小节,了解下决定这个设计的背后原因)

2

在每个`` {% for %}``循环里有一个称为`` forloop`` 的模板变量。这个变量有一些提示循环进度信息的属性。

forloop.counter 总是一个表示当前循环的执行次数的整数计数器。 这个计数器是从1开始的,所以在第一次循环时 forloop.counter 将会被设置为1。

{% for item in todo_list %}
    <p>{{ forloop.counter }}: {{ item }}</p>
{% endfor %}

forloop.counter0 类似于 forloop.counter ,但是它是从0计数的。 第一次执行循环时这个变量会被设置为0。

6

forloop.revcounter 是表示循环中剩余项的整型变量。 在循环初次执行时 forloop.revcounter 将被设置为序列中项的总数。 最后一次循环执行中,这个变量将被置1。

forloop.revcounter0 类似于 forloop.revcounter ,但它以0做为结束索引。 在第一次执行循环时,该变量会被置为序列的项的个数减1。

forloop.first 是一个布尔值

forloop.last 是一个布尔值;在最后一次执行循环时被置为True

forloop.parentloop 是一个指向当前循环的上一级循环的 forloop 对象的引用(在嵌套循环的情况下)

注释

就像HTML或者Python,Django模板语言同样提供代码注释。 注释使用 {# #} :

{# This is a comment #}

注释的内容不会在模板渲染时输出。

用这种语法的注释不能跨越多行。 这个限制是为了提高模板解析的性能。 在下面这个模板中,输出结果和模板本身是 完全一样的(也就是说,注释标签并没有被解析为注释):

This is a {# this is not
a comment #}
test.

如果要实现多行注释,可以使用`` {% comment %}`` 模板标签,就像这样:

4

{% comment %}
This is a
multi-line comment.
{% endcomment %}

7.3过滤器

2

就象本章前面提到的一样,模板过滤器是在变量被显示前修改它的值的一个简单方法。 过滤器使用管道字符,如下所示:

{{ name|lower }}

过滤器的参数跟随冒号之后并且总是以双引号包含

 例如:

{{ bio|truncatewords:"30" }}

7.4模板继承

你可以根据需要使用任意多的继承次数。 使用继承的一种常见方式是下面的三层法:

  1. 创建 base.html 模板,在其中定义站点的主要外观感受。 这些都是不常修改甚至从不修改的部分。

  1. 为网站的每个区域创建 base_SECTION.html 模板(例如, base_photos.html 和 base_forum.html )。这些模板对base.html 进行拓展,并包含区域特定的风格与设计。

    1

  1. 为每种类型的页面创建独立的模板,例如论坛页面或者图片库。 这些模板拓展相应的区域模板。

这个方法可最大限度地重用代码,并使得向公共区域(如区域级的导航)添加内容成为一件轻松的工作。

以下是使用模板继承的一些诀窍:

  • 如果在模板中使用 {% extends %} ,必须保证其为模板中的第一个模板标记。 否则,模板继承将不起作用。

    3

  • 一般来说,基础模板中的 {% block %} 标签越多越好。 记住,子模板不必定义父模板中所有的代码块,因此你可以用合理的缺省值对一些代码块进行填充,然后只对子模板所需的代码块进行(重)定义。 俗话说,钩子越多越好。

    3

  • 如果发觉自己在多个模板之间拷贝代码,你应该考虑将该代码段放置到父模板的某个 {% block %} 中。

  • 如果你需要访问父模板中的块的内容,使用 {{ block.super }}这个标签吧,这一个魔法变量将会表现出父模板中的内容。 如果只想在上级代码块基础上添加内容,而不是全部重载,该变量就显得非常有用了。

    14

  • 不允许在同一个模板中定义多个同名的 {% block %} 。 存在这样的限制是因为block 标签的工作方式是双向的。 也就是说,block 标签不仅挖了一个要填的坑,也定义了在模板中这个坑所填充的内容。如果模板中出现了两个相同名称的 {% block %} 标签,父模板将无从得知要使用哪个块的内容。

    3

  • {% extends %} 对所传入模板名称使用的加载方法和 get_template() 相同。 也就是说,会将模板名称被添加到 TEMPLATE_DIRS 设置之后。

    3

  • 多数情况下, {% extends %} 的参数应该是字符串,但是如果直到运行时方能确定父模板名,这个参数也可以是个变量。 这使得你能够实现一些很酷的动态功能。

8. Model

当数据库在本机安装好后,且在settings.py里正确配置了后。可以敲下面的命令进入数据库的控制台。这条命令也可以用来显示当前django配置的是哪种数据库。
E:\Programming\Program_python\Practices\Django-ex\mysite>python manage.py dbshell

编写models

写好models后,可以用下面的命令验证模型的有效性:

python manage.py validate

validate 命令检查你的模型的语法和逻辑是否正确。 如果一切正常,你会看到 0 errors found 消息。如果出错,请检查你输入的模型代码。 错误输出会给出非常有用的错误信息来帮助你修正你的模型。


另外要注意一点,在真正向数据库写入数据前,一定要提前在数据库里把数据库建立起来,比如对于mysql来说,用 CREATE DATABASE语句。书中的例子应该创建create database books;books就是settings.py里你配置的数据库

下面是如何激活models

Activating models

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

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

But first we need to tell our project that the polls app is installed.

Philosophy

Django apps are “pluggable”: You can use an app in multiple projects, and you can distribute apps, because they don’t have to be tied to a given Django installation.

Edit the mysite/settings.py file again, and change the INSTALLED_APPS setting to include the string 'polls'. So it’ll look like this:

mysite/settings.py
INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'polls',
)

Now Django knows to include the polls app. Let’s run another command:

$ python manage.py makemigrations polls

You should see something similar to the following:

Migrations for 'polls':
  0001_initial.py:
    - Create model Question
    - Create model Choice
    - Add field question to choice

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.

There’s a command that will run the migrations for you and manage your database schema automatically - that’s called migrate, and we’ll come to it in a moment - but first, let’s see what SQL that migration would run. The sqlmigrate command takes migration names and returns their SQL:

$ python manage.py sqlmigrate polls 0001

You should see something similar to the following (we’ve reformatted it for readability):

BEGIN;
CREATE TABLE "polls_choice" (
    "id" serial NOT NULL PRIMARY KEY,
    "choice_text" varchar(200) NOT NULL,
    "votes" integer NOT NULL
);
CREATE TABLE "polls_question" (
    "id" serial NOT NULL PRIMARY KEY,
    "question_text" varchar(200) NOT NULL,
    "pub_date" timestamp with time zone NOT NULL
);
ALTER TABLE "polls_choice" ADD COLUMN "question_id" integer NOT NULL;
ALTER TABLE "polls_choice" ALTER COLUMN "question_id" DROP DEFAULT;
CREATE INDEX "polls_choice_7aa0f6ee" ON "polls_choice" ("question_id");
ALTER TABLE "polls_choice"
  ADD CONSTRAINT "polls_choice_question_id_246c99a640fbbd72_fk_polls_question_id"
    FOREIGN KEY ("question_id")
    REFERENCES "polls_question" ("id")
    DEFERRABLE INITIALLY DEFERRED;

COMMIT;

Note the following:

  • The exact output will vary depending on the database you are using. The example above is generated for PostgreSQL.
  • Table names are automatically generated by combining the name of the app (polls) and the lowercase name of the model – questionand choice. (You can override this behavior.)
  • Primary keys (IDs) are added automatically. (You can override this, too.)
  • By convention, Django appends "_id" to the foreign key field name. (Yes, you can override this, as well.)
  • The foreign key relationship is made explicit by a FOREIGN KEY constraint. Don’t worry about the DEFERRABLE parts; that’s just telling PostgreSQL to not enforce the foreign key until the end of the transaction.
  • It’s tailored to the database you’re using, so database-specific field types such as auto_increment (MySQL), serial (PostgreSQL), orinteger primary key autoincrement (SQLite) are handled for you automatically. Same goes for the quoting of field names – e.g., using double quotes or single quotes.
  • The sqlmigrate command doesn’t actually run the migration on your database - it just prints it to the screen so that you can see what SQL Django thinks is required. It’s useful for checking what Django is going to do or if you have database administrators who require SQL scripts for changes.

If you’re interested, you can also run python manage.py check; this checks for any problems in your project without making migrations or touching the database.

Now, run migrate again to create those model tables in your database:

$ python manage.py migrate
Operations to perform:
  Synchronize unmigrated apps: staticfiles, messages
  Apply all migrations: admin, contenttypes, polls, auth, sessions
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
  Installing custom SQL...
Running migrations:
  Rendering model states... DONE
  Applying <migration name>... OK

The migrate command takes all the migrations that haven’t been applied (Django tracks which ones are applied using a special table in your database called django_migrations) and runs them against your database - essentially, synchronizing the changes you made to your models with the schema in the database.

Migrations are very powerful and let you change your models over time, as you develop your project, without the need to delete your database or tables and make new ones - it specializes in upgrading your database live, without losing data. We’ll cover them in more depth in a later part of the tutorial, but for now, remember the three-step guide to making model changes:

The reason that there are separate commands to make and apply migrations is because you’ll commit migrations to your version control system and ship them with your app; they not only make your development easier, they’re also useable by other developers and in production.


9站点管理

Admin是如何工作的

在幕后,管理工具是如何工作的呢? 其实很简单。

5

当服务启动时,Django从`` url.py`` 引导URLconf,然后执行`` admin.autodiscover()`` 语句。 这个函数遍历INSTALLED_APPS配置,并且寻找相关的 admin.py文件。 如果在指定的app目录下找到admin.py,它就执行其中的代码。

7

在`` books`` 应用程序目录下的`` admin.py`` 文件中,每次调用`` admin.site.register()`` 都将那个模块注册到管理工具中。 管理工具只为那些明确注册了的模块显示一个编辑/修改的界面。

1

应用程序`` django.contrib.auth`` 包含自身的`` admin.py`` ,所以Users和Groups能在管理工具中自动显示。 其它的django.contrib应用程序,如django.contrib.redirects,其它从网上下在的第三方Django应用程序一样,都会自行添加到管理工具。

2

综上所述,管理工具其实就是一个Django应用程序,包含自己的模块、模板、视图和URLpatterns。 你要像添加自己的视图一样,把它添加到URLconf里面。 你可以在Django基本代码中的django/contrib/admin 目录下,检查它的模板、视图和URLpatterns,但你不要尝试直接修改其中的任何代码,因为里面有很多地方可以让你自定义管理工具的工作方式。 (如果你确实想浏览Django管理工具的代码,请谨记它在读取关于模块的元数据过程中做了些不简单的工作,因此最好花些时间阅读和理解那些代码。)








学习Django时,使用PyCharm作为开发工具可以提高效率。PyCharm是一款功能强大的Python集成开发环境,它提供了丰富的功能和工具,可以帮助开发者更好地编写和调试Django应用程序。 在学习Django的过程中,可以使用PyCharm创建Django项目,并使用其内置的Django支持功能来简化开发过程。PyCharm可以自动识别Django项目的结构,并提供代码补全、语法检查、调试等功能,帮助开发者更快地编写和调试代码。 此外,PyCharm还提供了集成的版本控制系统,如Git,可以方便地管理和追踪代码的变化。它还支持自动化测试和部署,可以帮助开发者更好地进行项目管理和发布。 总之,使用PyCharm作为开发工具可以提高Django学习的效率和便利性。它的强大功能和友好的用户界面使得开发者可以更专注于代码的编写和项目的开发。\[1\] \[2\] \[3\] #### 引用[.reference_title] - *1* *3* [PyCharm平台下初学Django框架](https://blog.csdn.net/howard2005/article/details/93491364)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [pycharm平台下的Django教程](https://blog.csdn.net/Sunshine_ZCC/article/details/73918408)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值