Kaydet (Commit) 3653466b authored tarafından João Luiz Lorencetti's avatar João Luiz Lorencetti Kaydeden (comit) Tim Graham

Fixed #24732 -- Reordered tutorial to cover basics before bells and whistles.

üst ad0f0daf
......@@ -41,12 +41,13 @@ Are you new to Django or to programming? This is the place to start!
:doc:`Installation <intro/install>`
* **Tutorial:**
:doc:`Part 1: Models <intro/tutorial01>` |
:doc:`Part 2: The admin site <intro/tutorial02>` |
:doc:`Part 1: Requests and responses <intro/tutorial01>` |
:doc:`Part 2: Models and the admin site <intro/tutorial02>` |
:doc:`Part 3: Views and templates <intro/tutorial03>` |
:doc:`Part 4: Forms and generic views <intro/tutorial04>` |
:doc:`Part 5: Testing <intro/tutorial05>` |
:doc:`Part 6: Static files <intro/tutorial06>`
:doc:`Part 6: Static files <intro/tutorial06>` |
:doc:`Part 7: Customizing the admin site <intro/tutorial07>`
* **Advanced Tutorials:**
:doc:`How to write reusable apps <intro/reusable-apps>` |
......
......@@ -15,6 +15,7 @@ place: read this material to quickly get up and running.
tutorial04
tutorial05
tutorial06
tutorial07
reusable-apps
whatsnext
contributing
......
This diff is collapsed.
This diff is collapsed.
......@@ -6,8 +6,8 @@ This tutorial begins where :doc:`Tutorial 2 </intro/tutorial02>` left off. We're
continuing the Web-poll application and will focus on creating the public
interface -- "views."
Philosophy
==========
Overview
========
A view is a "type" of Web page in your Django application that generally serves
a specific function and has a specific template. For example, in a blog
......@@ -58,130 +58,6 @@ URLconf maps URL patterns (described as regular expressions) to views.
This tutorial provides basic instruction in the use of URLconfs, and you can
refer to :mod:`django.core.urlresolvers` for more information.
Write your first view
=====================
Let's write the first view. Open the file ``polls/views.py``
and put the following Python code in it:
.. snippet::
:filename: polls/views.py
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
This is the simplest view possible in Django. To call the view, we need to map
it to a URL - and for this we need a URLconf.
To create a URLconf in the polls directory, create a file called ``urls.py``.
Your app directory should now look like::
polls/
__init__.py
admin.py
models.py
tests.py
urls.py
views.py
In the ``polls/urls.py`` file include the following code:
.. snippet::
:filename: polls/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]
The next step is to point the root URLconf at the ``polls.urls`` module. In
``mysite/urls.py`` insert an :func:`~django.conf.urls.include`, leaving you
with:
.. snippet::
:filename: mysite/urls.py
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^polls/', include('polls.urls')),
url(r'^admin/', include(admin.site.urls)),
]
.. admonition:: Doesn't match what you see?
If you're seeing ``admin.autodiscover()`` before the definition of
``urlpatterns``, you're probably using a version of Django that doesn't
match this tutorial version. You'll want to either switch to the older
tutorial or the newer Django version.
You have now wired an ``index`` view into the URLconf. Go to
http://localhost:8000/polls/ in your browser, and you should see the text
"*Hello, world. You're at the polls index.*", which you defined in the
``index`` view.
The :func:`~django.conf.urls.url` function is passed four arguments, two
required: ``regex`` and ``view``, and two optional: ``kwargs``, and ``name``.
At this point, it's worth reviewing what these arguments are for.
:func:`~django.conf.urls.url` argument: regex
---------------------------------------------
The term "regex" is a commonly used short form meaning "regular expression",
which is a syntax for matching patterns in strings, or in this case, url
patterns. Django starts at the first regular expression and makes its way down
the list, comparing the requested URL against each regular expression until it
finds one that matches.
Note that these regular expressions do not search GET and POST parameters, or
the domain name. For example, in a request to
``http://www.example.com/myapp/``, the URLconf will look for ``myapp/``. In a
request to ``http://www.example.com/myapp/?page=3``, the URLconf will also
look for ``myapp/``.
If you need help with regular expressions, see `Wikipedia's entry`_ and the
documentation of the :mod:`re` module. Also, the O'Reilly book "Mastering
Regular Expressions" by Jeffrey Friedl is fantastic. In practice, however,
you don't need to be an expert on regular expressions, as you really only need
to know how to capture simple patterns. In fact, complex regexes can have poor
lookup performance, so you probably shouldn't rely on the full power of regexes.
Finally, a performance note: these regular expressions are compiled the first
time the URLconf module is loaded. They're super fast (as long as the lookups
aren't too complex as noted above).
.. _Wikipedia's entry: http://en.wikipedia.org/wiki/Regular_expression
:func:`~django.conf.urls.url` argument: view
--------------------------------------------
When Django finds a regular expression match, Django calls the specified view
function, with an :class:`~django.http.HttpRequest` object as the first
argument and any “captured” values from the regular expression as other
arguments. If the regex uses simple captures, values are passed as positional
arguments; if it uses named captures, values are passed as keyword arguments.
We'll give an example of this in a bit.
:func:`~django.conf.urls.url` argument: kwargs
----------------------------------------------
Arbitrary keyword arguments can be passed in a dictionary to the target view. We
aren't going to use this feature of Django in the tutorial.
:func:`~django.conf.urls.url` argument: name
---------------------------------------------
Naming your URL lets you refer to it unambiguously from elsewhere in Django
especially templates. This powerful feature allows you to make global changes
to the url patterns of your project while only touching a single file.
Writing more views
==================
......@@ -287,7 +163,7 @@ you want, using whatever Python libraries you want.
All Django wants is that :class:`~django.http.HttpResponse`. Or an exception.
Because it's convenient, let's use Django's own database API, which we covered
in :doc:`Tutorial 1 </intro/tutorial01>`. Here's one stab at a new ``index()``
in :doc:`Tutorial 2 </intro/tutorial02>`. Here's one stab at a new ``index()``
view, which displays the latest 5 poll questions in the system, separated by
commas, according to publication date:
......@@ -318,20 +194,7 @@ Your project's :setting:`TEMPLATES` setting describes how Django will load and
render templates. The default settings file configures a ``DjangoTemplates``
backend whose :setting:`APP_DIRS <TEMPLATES-APP_DIRS>` option is set to
``True``. By convention ``DjangoTemplates`` looks for a "templates"
subdirectory in each of the :setting:`INSTALLED_APPS`. This is how Django
knows to find the polls templates even though we didn't modify the
:setting:`DIRS <TEMPLATES-DIRS>` option, as we did in :ref:`Tutorial 2
<ref-customizing-your-projects-templates>`.
.. admonition:: Organizing templates
We *could* have all our templates together, in one big templates directory,
and it would work perfectly well. However, this template belongs to the
polls application, so unlike the admin template we created in the previous
tutorial, we'll put this one in the application's template directory
(``polls/templates``) rather than the project's (``templates``). We'll
discuss in more detail in the :doc:`reusable apps tutorial
</intro/reusable-apps>` *why* we do this.
subdirectory in each of the :setting:`INSTALLED_APPS`.
Within the ``templates`` directory you have just created, create another
directory called ``polls``, and within that create a file called
......@@ -390,8 +253,8 @@ context. The context is a dictionary mapping template variable names to Python
objects.
Load the page by pointing your browser at "/polls/", and you should see a
bulleted-list containing the "What's up" question from Tutorial 1. The link points
to the question's detail page.
bulleted-list containing the "What's up" question from :doc:`Tutorial 2
</intro/tutorial02>`. The link points to the question's detail page.
A shortcut: :func:`~django.shortcuts.render`
--------------------------------------------
......
......@@ -129,18 +129,19 @@ This code includes a few things we haven't covered yet in this tutorial:
This function helps avoid having to hardcode a URL in the view function.
It is given the name of the view that we want to pass control to and the
variable portion of the URL pattern that points to that view. In this
case, using the URLconf we set up in Tutorial 3, this
:func:`~django.core.urlresolvers.reverse` call will return a string like
case, using the URLconf we set up in :doc:`Tutorial 3 </intro/tutorial03>`,
this :func:`~django.core.urlresolvers.reverse` call will return a string like
::
'/polls/3/results/'
... where the ``3`` is the value of ``p.id``. This redirected URL will
where the ``3`` is the value of ``p.id``. This redirected URL will
then call the ``'results'`` view to display the final page.
As mentioned in Tutorial 3, ``request`` is a :class:`~django.http.HttpRequest`
object. For more on :class:`~django.http.HttpRequest` objects, see the
:doc:`request and response documentation </ref/request-response>`.
As mentioned in :doc:`Tutorial 3 </intro/tutorial03>`, ``request`` is an
:class:`~django.http.HttpRequest` object. For more on
:class:`~django.http.HttpRequest` objects, see the :doc:`request and
response documentation </ref/request-response>`.
After somebody votes in a question, the ``vote()`` view redirects to the results
page for the question. Let's write that view:
......@@ -183,7 +184,7 @@ Use generic views: Less code is better
The ``detail()`` (from :doc:`Tutorial 3 </intro/tutorial03>`) and ``results()``
views are very simple -- and, as mentioned above, redundant. The ``index()``
view (also from Tutorial 3), which displays a list of polls, is similar.
view, which displays a list of polls, is similar.
These views represent a common case of basic Web development: getting data from
the database according to a parameter passed in the URL, loading a template and
......@@ -237,8 +238,6 @@ First, open the ``polls/urls.py`` URLconf and change it like so:
Note that the name of the matched pattern in the regexes of the second and third
patterns has changed from ``<question_id>`` to ``<pk>``.
.. _tutorial04-amend-views:
Amend views
-----------
......
......@@ -18,7 +18,7 @@ Testing operates at different levels. Some tests might apply to a tiny detail
(*does a particular model method return values as expected?*) while others
examine the overall operation of the software (*does a sequence of user inputs
on the site produce the desired result?*). That's no different from the kind of
testing you did earlier in :doc:`Tutorial 1 </intro/tutorial01>`, using the
testing you did earlier in :doc:`Tutorial 2 </intro/tutorial02>`, using the
:djadmin:`shell` to examine the behavior of a method, or running the
application and entering data to check how it behaves.
......@@ -134,10 +134,8 @@ right away: the ``Question.was_published_recently()`` method returns ``True`` if
the ``Question`` was published within the last day (which is correct) but also if
the ``Question``’s ``pub_date`` field is in the future (which certainly isn't).
You can see this in the Admin; create a question whose date lies in the future;
you'll see that the ``Question`` change list claims it was published recently.
You can also see this using the :djadmin:`shell`::
To check if the bug really exists, using the Admin create a question whose date
lies in the future and check the method using the :djadmin:`shell`::
>>> import datetime
>>> from django.utils import timezone
......@@ -393,7 +391,7 @@ Improving our view
The list of polls shows polls that aren't published yet (i.e. those that have a
``pub_date`` in the future). Let's fix that.
In :ref:`Tutorial 4 <tutorial04-amend-views>` we introduced a class-based view,
In :doc:`Tutorial 4 </intro/tutorial04>` we introduced a class-based view,
based on :class:`~django.views.generic.list.ListView`:
.. snippet::
......
......@@ -116,13 +116,6 @@ with the framework see
static files </howto/static-files/deployment>` discusses how to use static
files on a real server.
What's next?
============
The beginner tutorial ends here for the time being. In the meantime, you might
want to check out some pointers on :doc:`where to go from here
</intro/whatsnext>`.
If you are familiar with Python packaging and interested in learning how to
turn polls into a "reusable app", check out :doc:`Advanced tutorial: How to
write reusable apps</intro/reusable-apps>`.
When you're comfortable with the static files, read :doc:`part 7 of this
tutorial </intro/tutorial07>` to learn how to customize Django's
automatically-generated admin site.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment