django第一篇
摘要:
1 Django是一个开放源代码的Web应用框架,由Python写成。采用了MVC的软件设计模式,即模型M,视图V和控制器C。模型即后端逻辑,视图就是url对应的前端展示
2本文简介了使用模型和视图搭建一个网站的例子。
Django at a glance
Because Django was developed in a fast-paced newsroom environment, it was designed to make common Web-development tasks fast and easy. Here’s an informal overview of how to write a database-driven Web app with Django.
The goal of this document is to give you enough technical specifics to understand how Django works, but this isn’t intended to be a tutorial or reference – but we’ve got both! When you’re ready to start a project, you can start
with the tutorial or dive right into more detailed documentation.
1 Design your model 设计模型
Although you can use Django without a database, it comes with an object-relational mapper in which you describe your database layout in Python code.
The data-model syntax offers many rich ways of representing
your models – so far, it’s been solving two years’ worth of database-schema problems. Here’s a quick example, which might be saved in the filemysite/news/models.py:
class Reporter(models.Model):
full_name = models.CharField(max_length=70) def __unicode__(self):
return self.full_name class Article(models.Model):
pub_date = models.DateTimeField()
headline = models.CharField(max_length=200)
content = models.TextField()
reporter = models.ForeignKey(Reporter) def __unicode__(self):
return self.headline
Install it
Next, run the Django command-line utility to create the database tables automatically:
manage.py syncdb
The syncdb command
looks at all your available models and creates tables in your database for whichever tables don’t already exist.
Enjoy the free API
With that, you’ve got a free, and rich, Python API to access
your data. The API is created on the fly, no code generation necessary:
# Import the models we created from our "news" app
>>> from news.models import Reporter, Article # No reporters are in the system yet.
>>> Reporter.objects.all()
[] # Create a new Reporter.
>>> r = Reporter(full_name='John Smith') # Save the object into the database. You have to call save() explicitly.
>>> r.save() # Now it has an ID.
>>> r.id
1 # Now the new reporter is in the database.
>>> Reporter.objects.all()
[<Reporter: John Smith>] # Fields are represented as attributes on the Python object.
>>> r.full_name
'John Smith' # Django provides a rich database lookup API.
>>> Reporter.objects.get(id=1)
<Reporter: John Smith>
>>> Reporter.objects.get(full_name__startswith='John')
<Reporter: John Smith>
>>> Reporter.objects.get(full_name__contains='mith')
<Reporter: John Smith>
>>> Reporter.objects.get(id=2)
Traceback (most recent call last):
...
DoesNotExist: Reporter matching query does not exist. # Create an article.
>>> from datetime import datetime
>>> a = Article(pub_date=datetime.now(), headline='Django is cool',
... content='Yeah.', reporter=r)
>>> a.save() # Now the article is in the database.
>>> Article.objects.all()
[<Article: Django is cool>] # Article objects get API access to related Reporter objects.
>>> r = a.reporter
>>> r.full_name
'John Smith' # And vice versa: Reporter objects get API access to Article objects.
>>> r.article_set.all()
[<Article: Django is cool>] # The API follows relationships as far as you need, performing efficient
# JOINs for you behind the scenes.
# This finds all articles by a reporter whose name starts with "John".
>>> Article.objects.filter(reporter__full_name__startswith="John")
[<Article: Django is cool>] # Change an object by altering its attributes and calling save().
>>> r.full_name = 'Billy Goat'
>>> r.save() # Delete an object with delete().
>>> r.delete()
A dynamic admin interface: it’s not just scaffolding – it’s the whole house
Once your models are defined, Django can automatically create a professional, production readyadministrative
interface – a Web site that lets authenticated users add, change and delete objects. It’s as easy as registering your model in the admin site:
# In models.py... from django.db import models class Article(models.Model):
pub_date = models.DateTimeField()
headline = models.CharField(max_length=200)
content = models.TextField()
reporter = models.ForeignKey(Reporter) # In admin.py in the same directory... import models
from django.contrib import admin admin.site.register(models.Article)
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.
2 Design your URLs(设计url,即设计控制)
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:
from django.conf.urls import patterns, url, include urlpatterns = patterns('',
(r'^articles/(\d{4})/$', 'news.views.year_archive'),
(r'^articles/(\d{4})/(\d{2})/$', 'news.views.month_archive'),
(r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'news.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 functionnews.views.article_detail(request, '2005', '05', '39323').
3 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:
def year_archive(request, year):
a_list = Article.objects.filter(pub_date__year=year)
return render_to_response('news/year_archive.html', {'year': year, 'article_list': a_list})
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. 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:
{% 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; yes, there is one good idea
in PHP).
You can chain together as many filters as you’d like. You can write custom 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 might look like:
<html>
<head>
<title>{% block title %}{% endblock %}</title>
</head>
<body>
<img src="sitelogo.gif" alt="Logo" />
{% block content %}{% endblock %}
</body>
</html>
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 cell-phone editions 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!
转自:http://django-chinese-docs-14.readthedocs.org/en/latest/intro/overview.html
django第一篇的更多相关文章
- <Django>第一篇:入门的例子
1.MVT框架 Model(模型):数据库交互相关.在这部分一般需要进行三个操作: (1)面向数据库:模型对象.列表 (2)定义模型类:指定属性及类型,确定表结构(设计表),需要迁移(生成表) (3) ...
- 第一篇:Win10系统搭建Python+Django+Nginx+MySQL 开发环境详解(完美版)
Win10+Python+Django+Nginx+MySQL 开发环境搭建详解 PaulTsao 说明:本文由作者原创,仅供内部参考学习与交流,转载引用请注明出处,用于商业目的请联系作者本人. Wi ...
- 第一篇:Django基础
Django框架第一篇基础 一个小问题: 什么是根目录:就是没有路径,只有域名..url(r'^$') 补充一张关于wsgiref模块的图片 一.MTV模型 Django的MTV分别代表: Model ...
- Django之模型层第一篇:单表操作
Django之模型层第一篇:单表操作 一 ORM简介 我们在使用Django框架开发web应用的过程中,不可避免地会涉及到数据的管理操作(如增.删.改.查),而一旦谈到数据的管理操作,就需要用到数 ...
- Python开发【第一篇】:目录
本系列博文包含 Python基础.前端开发.Web框架.缓存以及队列等,希望可以给正在学习编程的童鞋提供一点帮助!!! Python开发[第一篇]:目录 Python开发[第二篇]:初识Python ...
- 第一篇 Flask
第一篇 Flask 一. Python 现阶段三大主流Web框架 Django Tornado Flask 对比 1.Django 主要特点是大而全,集成了很多组件,例如: Models Ad ...
- Flask最强攻略 - 跟DragonFire学Flask - 第一篇 你好,我叫Flask
首先,要看你学没学过Django 如果学过Django 的同学,请从头看到尾,如果没有学过Django的同学,并且不想学习Django的同学,轻饶过第一部分 一. Python 现阶段三大主流Web框 ...
- Python编程笔记(第一篇)Python基础语法
一.python介绍 1.编程语言排行榜 TIOBE榜 TIOBE编程语言排行榜是编程语言流行趋势的一个指标,每月更新,这份排行榜排名基于互联网有经验的程序员.课程和第三方厂商的数量. 2.pytho ...
- 01: Django基础篇
目录:Django其他篇 01:Django基础篇 02:Django进阶篇 03:Django数据库操作--->Model 04: Form 验证用户数据 & 生成html 05:Mo ...
随机推荐
- ASP.NET MVC View向Controller提交数据
我们知道使用MVC的一个很重的的用途就是把Controller和View之间进行解耦,通过控制器来调用不同的视图,这就注定了Controller和View之间的传值是一个很重的知识点,这篇博文主要解释 ...
- nefu 449 超级楼梯 &&nefu 911 跨楼梯
nefu 449 超级楼梯 Description 有一楼梯共M级,刚开始时你在第一级,若每次只能跨上一级或二级,要走上第M级,共有多少种走法? Input 输入数据首先包含一个整数N,表示测试实例的 ...
- 命令 shell 学习
for i in a b c do echo $i done !ser 历史补全 > 正确信息输出文件 >>正确信息输出文件 ,追加 2>错误信息输出文件 2>> ...
- iOS应用程序内存查看工具
我要找的是一个可以检查应用程序中哪一个数组存贮的什么内容的工具. 网上搜到的工具名称是Allocations Instrument,后来一试发现不是我想要的.这还是一个后期调试阶段的内存检查工具. h ...
- Masonry使用详解
mas_makeConstraints 只负责新增约束 Autolayout不能同时存在两条针对于同一对象的约束 否则会报错 mas_updateConstraints 针对上面的情况 会更新在blo ...
- 关于Spring Security 3获取用户信息的问题
标签: spring security 3标签获取用户信息 2013-01-05 10:40 5342人阅读 评论(0) 收藏 举报 分类: Spring(25) java(70) 前端(7) ...
- robots.txt 文件指南
http://robots.51240.com/ robots 生成器
- 从运营商小广告到HTTPS
相信很多人都试过这样的经历,浏览一个正常的网站时,右下突然角弹出一堆小广告,而且这些广告的内容和你浏览的网站格格不入: 前几天还有某微博用户爆料访问github时居然也有广告: 又或者,你有没有试过因 ...
- C++左值
C++左值 左值参数是可被引用的数据对象.比如,变量,数组元素,结构成员,引用和解引用指针 非左值包含字面常量(用引号括起的字符串除外,它们是由地址表示的)和包含多项的表达式 在C语言里面左值最初指的 ...
- Jdk1.7环境变量的配置
在"系统属性——高级——环境变量——系统变量"中新建如下变量: 变量名:JAVA_HOME 变量值:C:\Program Files\Java\jdk1.7.0_03 (即jdk ...