您现在所在的位置:首页 >学习资源 > Python全栈+人工智能入门教材 > Python基础入门教程67:Django

Python基础入门教程67:Django

来源:奇酷教育 发表于:

Django 项目是一个定制框架,它源自一个在线新闻 Web 站点,于 2005 年以开源的形式被释放出来。Django 框架的核心组件有:用于创建

Django 项目是一个定制框架,它源自一个在线新闻 Web 站点,于 2005 年以开源的形式被释放出来。Django 框架的核心组件有:
  • 用于创建模型的对象关系映射
  • 为最终用户设计的完美管理界面
  • 一流的 URL 设计
  • 设计者友好的模板语言
  • 缓存系统

本文是有关 Python Web 框架的由两篇文章组成的系列文章的第一篇。第二篇文章将向您介绍 TurboGears 框架。

要使用并理解本文中提供的代码,则需要安装 Python,并了解在初学者的水平上如何使用 Python。要查看是否安装了 Python 以及 Python 的版本号,可以输入 python -V。Django 至少需要 2.3.5 版本的 Python,可以从 Python Web 站点上下载它(关于链接请参阅本文后面 参考资料 部分)。我们至少还应该顺便熟悉一下 MVC 架构。

安装 Django

本文使用了 Django 的开发版本,以便能够利用 Django 框架的最新改进。建议您在 0.95 版正式发布之前使用这个版本。关于最新发行版本,请参阅 Django 的 Web 站点(再次请您参阅 参考资料 来获得链接)。

按照以下步骤下载并安装 Django:

清单 1. 下载并安装 Django
1
2
3
~/downloads# svn co http://code.djangoproject.com/svn/django/trunk/ django_src
~/downloads# cd django_src
~/downloads# python setup.py install

Django 管理工具

在安装 Django 之后,您现在应该已经有了可用的管理工具 django-admin.py。清单 2 给出了这个管理工具中可以使用的一些命令:

清单 2. 使用 Django 管理工具
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
~/dev$ django-admin.py
usage: django-admin.py action [options]
actions:
  adminindex [modelmodule ...]
    Prints the admin-index template snippet for the given model
    module name(s).
 
  ... snip ...
 
  startapp [appname]
    Creates a Django app directory structure for the given app name
    in the current directory.
 
  startproject [projectname]
    Creates a Django project directory structure for the given
    project name in the current directory.
 
  validate
    Validates all installed models.
 
options:
  -h, --help        show this help message and exit
  --settings=SETTINGS   Python path to settings module, e.g.
            "myproject.settings.main". If this isn't
            provided, the DJANGO_SETTINGS_MODULE
            environment variable will be used.
  --pythonpath=PYTHONPATH
            Lets you manually add a directory the Python
            path, e.g. "/home/djangoprojects/myproject".