没有合适的资源?快使用搜索试试~ 我知道了~
首页Django 1.11.1官方指南:快速入门与核心功能详解
Django 1.11.1官方指南:快速入门与核心功能详解
需积分: 19 79 下载量 35 浏览量
更新于2024-07-20
3
收藏 6.28MB PDF 举报
Django使用指南是一份详尽的官方文档,适用于初学者和有经验的开发者,由Django Software Foundation发布于2017年5月3日。这份文档涵盖了Django框架的核心组件和开发流程,以及如何快速上手、编写第一个Django应用,并提供了高级主题如可重用应用开发和后续学习路径。
1. **文档结构与获取帮助**:
- 文档首先介绍如何获取帮助,包括官方文档网站、邮件列表和社区论坛,以便用户在遇到问题时能够找到相应的支持资源。
2. **核心组件详解**:
- **模odel层**: Django的模型定义了数据结构和数据库交互,是应用程序的核心逻辑部分。
- **视图层**: 视图处理用户的请求,将数据转化为合适的HTTP响应,实现业务逻辑的执行。
- **模板层**: 这是用户界面的构建者,允许开发者通过简单的语法操作数据并渲染HTML输出。
- **表单**: Django提供了强大的表单处理能力,用于用户输入验证和数据提交。
- **开发过程**: 涵盖了测试、部署和持续集成等关键环节,确保代码质量和效率。
3. **管理后台与安全性**:
- Django Admin提供了一个内置的管理界面,方便管理数据和模型对象。
- 安全性方面,文档强调了认证、授权和安全配置的重要性,确保应用程序的安全性。
4. **国际化与性能优化**:
- 国际化和本地化支持多语言环境,使得应用能够适应不同的地域需求。
- 性能优化建议包括数据库查询优化、缓存策略和负载均衡等。
5. **兼容性与扩展**:
- Django的Python兼容性,确保其能够在各种版本的Python环境中运行。
- 地理定位框架和常见Web应用工具的集成,为开发提供更多可能性。
6. **其他核心功能**:
- 提供了对会话管理、中间件、URL路由等高级特性的深入讲解。
7. **项目入门教程**:
- 从概览Django的工作原理开始,引导读者逐步编写自己的第一个Django应用,分为多个部分,涉及设置环境、创建应用、配置、数据模型、视图和模板等步骤。
- 高级教程则深入探讨如何创建可复用的库或应用,提升开发效率。
8. **后续阅读推荐**:
- 文档最后为那些已经掌握了基础的开发者提供了进一步学习的资源,包括深入主题和进阶技术。
Django使用指南是一份全面且循序渐进的学习资料,无论是初次接触Django的开发者,还是希望深化理解框架的资深开发者,都能从中获益良多。
Django Documentation, Release 1.11.1.dev20170503001739
The philosophy here is that your site is edited by a staff, or a client, or maybe just you – and you don’t want to have to
deal with creating backend interfaces just to manage content.
One typical workflow in creating Django apps is to create models and get the admin sites up and running as fast as
possible, so your staff (or clients) can start populating data. Then, develop the way data is presented to the public.
Design your URLs
A clean, elegant URL scheme is an important detail in a high-quality Web application. Django encourages beautiful
URL design and doesn’t put any cruft in URLs, like .php or .asp.
To design URLs for an app, you create a Python module called a URLconf . A table of contents for your app, it contains
a simple mapping between URL patterns and Python callback functions. URLconfs also serve to decouple URLs from
Python code.
Here’s what a URLconf might look like for the Reporter/Article example above:
mysite/news/urls.py
from django.conf.urls import url
from . import views
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 imports and calls the given view, which is a simple 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').
Write your views
Each view is responsible for doing one of two things: Returning an HttpResponse object containing the content
for the requested page, or raising an exception such as Http404. The rest is up to you.
Generally, a view retrieves data according to the parameters, loads a template and renders the template with the
retrieved data. Here’s an example view for year_archive from above:
mysite/news/views.py
from django.shortcuts import render
from .models import Article
def year_archive(request, year):
a_list = Article.objects.filter(pub_date__year=year)
context = {'year': year, 'article_list': a_list}
return render(request, 'news/year_archive.html', context)
10 Chapter 2. Getting started
Django Documentation, Release 1.11.1.dev20170503001739
This example uses Django’s template system, which has several powerful features but strives to stay simple enough
for non-programmers to use.
Design your templates
The code above loads the news/year_archive.html template.
Django has a template search path, which allows you to minimize redundancy among templates. In your Django
settings, you specify a list of directories to check for templates with DIRS. If a template doesn’t exist in the first
directory, it checks the second, and so on.
Let’s say the news/year_archive.html template was found. Here’s what that might look like:
mysite/news/templates/news/year_archive.html
{% extends "base.html" %}
{% block title %}Articles for {{ year }}{% endblock %}
{% block content %}
<h1>Articles for {{ year }}</h1>
{% for article in article_list %}
<p>{{ article.headline }}</p>
<p>By {{ article.reporter.full_name }}</p>
<p>Published {{ article.pub_date|date:"F j, Y" }}</p>
{% endfor %}
{% endblock %}
Variables are surrounded by double-curly braces. {{ article.headline }} means “Output the value of the
article’s headline attribute.” But dots aren’t used only for attribute lookup. They also can do dictionary-key lookup,
index lookup and function calls.
Note {{ article.pub_date|date:"F j, Y" }} uses a Unix-style “pipe” (the “|” character). This is called
a template filter, and it’s a way to filter the value of a variable. In this case, the date filter formats a Python datetime
object in the given format (as found in PHP’s date function).
You can chain together as many filters as you’d like. You can write custom template filters. You can write custom
template tags, which run custom Python code behind the scenes.
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.
Here’s what the “base.html” template, including the use of static files, might look like:
mysite/templates/base.html
{% load static %}
<html>
<head>
<title>{% block title %}{% endblock %}</title>
</head>
<body>
<img src="{% static "images/sitelogo.png" %}" alt="Logo" />
{% block content %}{% endblock %}
</body>
</html>
2.1. Django at a glance 11
Django Documentation, Release 1.11.1.dev20170503001739
Simplistically, it defines the look-and-feel of the site (with the site’s logo), and provides “holes” for child templates to
fill. This makes a site redesign as easy as changing a single file – the base 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.
Note that you don’t have to use Django’s template system if you prefer another system. While Django’s template
system is particularly well-integrated with Django’s model layer, nothing forces you to use it. For that matter, you
don’t have to use Django’s database API, either. You can use another database abstraction layer, you can read XML
files, you can read files off disk, or anything you want. Each piece of Django – models, views, templates – is decoupled
from the next.
This is just the surface
This has been only a quick overview of Django’s functionality. Some more useful features:
• A caching framework that integrates with memcached or other backends.
• A syndication framework that makes creating RSS and Atom feeds as easy as writing a small Python class.
• More sexy automatically-generated admin features – this overview barely scratched the surface.
The next obvious steps are for you to download Django, read the tutorial and join the community. Thanks for your
interest!
Quick install guide
Before you can use Django, you’ll need to get it installed. We have a complete installation guide that covers all
the possibilities; this guide will guide you to a simple, minimal installation that’ll work while you walk through the
introduction.
Install Python
Being a Python Web framework, Django requires Python. See What Python version can I use with Django? for details.
Python includes a lightweight database called SQLite so you won’t need to set up a database just yet.
Get the latest version of Python at https://www.python.org/download/ or with your operating system’s package man-
ager.
Django on Jython
If you use Jython (a Python implementation for the Java platform), you’ll need to follow a few additional steps. See
Running Django on Jython for details.
You can verify that Python is installed by typing python from your shell; you should see something like:
Python 3.4.x
[GCC 4.x] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
12 Chapter 2. Getting started
Django Documentation, Release 1.11.1.dev20170503001739
Set up a database
This step is only necessary if you’d like to work with a “large” database engine like PostgreSQL, MySQL, or Oracle.
To install such a database, consult the database installation information.
Remove any old versions of 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.
Install Django
You’ve got three easy options to install Django:
• Install an official release. This is the best approach for most users.
• Install a version of Django provided by your operating system distribution.
• Install the latest development version. This option is for enthusiasts who want the latest-and-greatest features
and aren’t afraid of running brand new code. You might encounter new bugs in the development version, but
reporting them helps the development of Django. Also, releases of third-party packages are less likely to be
compatible with the development version than with the latest stable release.
Always refer to the documentation that corresponds to the version of Django you’re using!
If you do either of the first two steps, keep an eye out for parts of the documentation marked new in development
version. That phrase flags features that are only available in development versions of Django, and they likely won’t
work with an official release.
Verifying
To verify that Django can be seen by Python, type python from your shell. Then at the Python prompt, try to import
Django:
>>> import django
>>> print(django.get_version())
1.11
You may have another version of Django installed.
That’s it!
That’s it – you can now move onto the tutorial.
Writing your first Django app, part 1
Let’s learn by example.
Throughout this tutorial, we’ll walk you through the creation of a basic poll application.
It’ll consist of two parts:
2.3. Writing your first Django app, part 1 13
Django Documentation, Release 1.11.1.dev20170503001739
• A public site that lets people view polls and vote in them.
• An admin site that lets you add, change, and delete polls.
We’ll assume you have Django installed already. You can tell Django is installed and which version by running the
following command in a shell prompt (indicated by the $ prefix):
$ python -m django --version
If Django is installed, you should see the version of your installation. If it isn’t, you’ll get an error telling “No module
named django”.
This tutorial is written for Django 1.11 and Python 3.4 or later. If the Django version doesn’t match, you can refer to
the tutorial for your version of Django by using the version switcher at the bottom right corner of this page, or update
Django to the newest version. If you are still using Python 2.7, you will need to adjust the code samples slightly, as
described in comments.
See How to install Django for advice on how to remove older versions of Django and install a newer one.
Where to get help:
If you’re having trouble going through this tutorial, please post a message to django-users or drop by #django on
irc.freenode.net to chat with other Django users who might be able to help.
Creating a project
If this is your first time using Django, you’ll have to take care of some initial setup. Namely, you’ll need to auto-
generate some code that establishes a Django project – a collection of settings for an instance of Django, including
database configuration, Django-specific options and application-specific settings.
From the command line, cd into a directory where you’d like to store your code, then run the following command:
$ django-admin startproject mysite
This will create a mysite directory in your current directory. If it didn’t work, see Problems running django-admin.
Note: You’ll need to avoid naming projects after built-in Python or Django components. In particular, this means
you should avoid using names like django (which will conflict with Django itself) or test (which conflicts with a
built-in Python package).
Where should this code live?
If your background is in plain old PHP (with no use of modern frameworks), you’re probably used to putting code
under the Web server’s document root (in a place such as /var/www). With Django, you don’t do that. It’s not a
good idea to put any of this Python code within your Web server’s document root, because it risks the possibility that
people may be able to view your code over the Web. That’s not good for security.
Put your code in some directory outside of the document root, such as /home/mycode.
Let’s look at what startproject created:
mysite/
manage.py
mysite/
14 Chapter 2. Getting started
剩余1843页未读,继续阅读
Scnu_wang
- 粉丝: 44
- 资源: 26
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
最新资源
- 多模态联合稀疏表示在视频目标跟踪中的应用
- Kubernetes资源管控与Gardener开源软件实践解析
- MPI集群监控与负载平衡策略
- 自动化PHP安全漏洞检测:静态代码分析与数据流方法
- 青苔数据CEO程永:技术生态与阿里云开放创新
- 制造业转型: HyperX引领企业上云策略
- 赵维五分享:航空工业电子采购上云实战与运维策略
- 单片机控制的LED点阵显示屏设计及其实现
- 驻云科技李俊涛:AI驱动的云上服务新趋势与挑战
- 6LoWPAN物联网边界路由器:设计与实现
- 猩便利工程师仲小玉:Terraform云资源管理最佳实践与团队协作
- 类差分度改进的互信息特征选择提升文本分类性能
- VERITAS与阿里云合作的混合云转型与数据保护方案
- 云制造中的生产线仿真模型设计与虚拟化研究
- 汪洋在PostgresChina2018分享:高可用 PostgreSQL 工具与架构设计
- 2018 PostgresChina大会:阿里云时空引擎Ganos在PostgreSQL中的创新应用与多模型存储
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功