Refs #30573 -- Rephrased "Of Course" and "Obvious(ly)" in documentation and comments.

This commit is contained in:
Adam Johnson 2020-05-01 13:37:21 +01:00 committed by Mariusz Felisiak
parent 787981f9d1
commit d17b380653
48 changed files with 137 additions and 160 deletions

View File

@ -104,7 +104,7 @@ class ContentTypeManager(models.Manager):
def get_for_id(self, id): def get_for_id(self, id):
""" """
Lookup a ContentType by ID. Use the same shared cache as get_for_model Lookup a ContentType by ID. Use the same shared cache as get_for_model
(though ContentTypes are obviously not created on-the-fly by get_by_id). (though ContentTypes are not created on-the-fly by get_by_id).
""" """
try: try:
ct = self._cache[self.db][id] ct = self._cache[self.db][id]

View File

@ -4,9 +4,9 @@ from django.db.backends.oracle.introspection import DatabaseIntrospection
class OracleIntrospection(DatabaseIntrospection): class OracleIntrospection(DatabaseIntrospection):
# Associating any OBJECTVAR instances with GeometryField. Of course, # Associating any OBJECTVAR instances with GeometryField. This won't work
# this won't work right on Oracle objects that aren't MDSYS.SDO_GEOMETRY, # right on Oracle objects that aren't MDSYS.SDO_GEOMETRY, but it is the
# but it is the only object type supported within Django anyways. # only object type supported within Django anyways.
data_types_reverse = DatabaseIntrospection.data_types_reverse.copy() data_types_reverse = DatabaseIntrospection.data_types_reverse.copy()
data_types_reverse[cx_Oracle.OBJECT] = 'GeometryField' data_types_reverse[cx_Oracle.OBJECT] = 'GeometryField'

View File

@ -89,8 +89,8 @@ class MigrationAutodetector:
def only_relation_agnostic_fields(self, fields): def only_relation_agnostic_fields(self, fields):
""" """
Return a definition of the fields that ignores field names and Return a definition of the fields that ignores field names and
what related fields actually relate to. Used for detecting renames (as, what related fields actually relate to. Used for detecting renames (as
of course, the related fields change during renames). the related fields change during renames).
""" """
fields_def = [] fields_def = []
for name, field in sorted(fields.items()): for name, field in sorted(fields.items()):
@ -676,9 +676,8 @@ class MigrationAutodetector:
def generate_created_proxies(self): def generate_created_proxies(self):
""" """
Make CreateModel statements for proxy models. Use the same statements Make CreateModel statements for proxy models. Use the same statements
as that way there's less code duplication, but of course for proxy as that way there's less code duplication, but for proxy models it's
models it's safe to skip all the pointless field stuff and just chuck safe to skip all the pointless field stuff and chuck out an operation.
out an operation.
""" """
added = self.new_proxy_keys - self.old_proxy_keys added = self.new_proxy_keys - self.old_proxy_keys
for app_label, model_name in sorted(added): for app_label, model_name in sorted(added):

View File

@ -11,7 +11,7 @@ class LocaleMiddleware(MiddlewareMixin):
""" """
Parse a request and decide what translation object to install in the Parse a request and decide what translation object to install in the
current thread context. This allows pages to be dynamically translated to current thread context. This allows pages to be dynamically translated to
the language the user desires (if the language is available, of course). the language the user desires (if the language is available).
""" """
response_redirect_class = HttpResponseRedirect response_redirect_class = HttpResponseRedirect

View File

@ -699,7 +699,7 @@ def firstof(parser, token):
{{ var3 }} {{ var3 }}
{% endif %} {% endif %}
but obviously much cleaner! but much cleaner!
You can also use a literal string as a fallback value in case all You can also use a literal string as a fallback value in case all
passed variables are False:: passed variables are False::

View File

@ -120,9 +120,9 @@ If you're hungry for acronyms, you might say that Django is a "MTV" framework
-- that is, "model", "template", and "view." That breakdown makes much more -- that is, "model", "template", and "view." That breakdown makes much more
sense. sense.
At the end of the day, of course, it comes down to getting stuff done. And, At the end of the day, it comes down to getting stuff done. And, regardless of
regardless of how things are named, Django gets stuff done in a way that's most how things are named, Django gets stuff done in a way that's most logical to
logical to us. us.
<Framework X> does <feature Y> -- why doesn't Django? <Framework X> does <feature Y> -- why doesn't Django?
===================================================== =====================================================
@ -167,11 +167,10 @@ It's a Web framework; it's a programming tool that lets you build websites.
For example, it doesn't make much sense to compare Django to something like For example, it doesn't make much sense to compare Django to something like
Drupal_, because Django is something you use to *create* things like Drupal. Drupal_, because Django is something you use to *create* things like Drupal.
Of course, Django's automatic admin site is fantastic and timesaving -- but Yes, Django's automatic admin site is fantastic and timesaving -- but the admin
the admin site is one module of Django the framework. Furthermore, although site is one module of Django the framework. Furthermore, although Django has
Django has special conveniences for building "CMS-y" apps, that doesn't mean special conveniences for building "CMS-y" apps, that doesn't mean it's not just
it's not just as appropriate for building "non-CMS-y" apps (whatever that as appropriate for building "non-CMS-y" apps (whatever that means!).
means!).
.. _Drupal: https://drupal.org/ .. _Drupal: https://drupal.org/

View File

@ -78,8 +78,8 @@ better supported, the latest version of Python 3 is recommended.
You don't lose anything in Django by using an older release, but you don't take You don't lose anything in Django by using an older release, but you don't take
advantage of the improvements and optimizations in newer Python releases. advantage of the improvements and optimizations in newer Python releases.
Third-party applications for use with Django are, of course, free to set their Third-party applications for use with Django are free to set their own version
own version requirements. requirements.
Should I use the stable version or development version? Should I use the stable version or development version?
======================================================= =======================================================

View File

@ -12,7 +12,7 @@ Make sure that:
* Said module is on ``sys.path`` (``import mysite.settings`` should work). * Said module is on ``sys.path`` (``import mysite.settings`` should work).
* The module doesn't contain syntax errors (of course). * The module doesn't contain syntax errors.
I can't stand your template language. Do I have to use it? I can't stand your template language. Do I have to use it?
========================================================== ==========================================================

View File

@ -301,10 +301,10 @@ than disappearing if they take on the old default value.
In addition, try to avoid returning values as positional arguments; where In addition, try to avoid returning values as positional arguments; where
possible, return values as keyword arguments for maximum future compatibility. possible, return values as keyword arguments for maximum future compatibility.
Of course, if you change the names of things more often than their position If you change the names of things more often than their position in the
in the constructor's argument list, you might prefer positional, but bear in constructor's argument list, you might prefer positional, but bear in mind that
mind that people will be reconstructing your field from the serialized version people will be reconstructing your field from the serialized version for quite
for quite a while (possibly years), depending how long your migrations live for. a while (possibly years), depending how long your migrations live for.
You can see the results of deconstruction by looking in migrations that include You can see the results of deconstruction by looking in migrations that include
the field, and you can test deconstruction in unit tests by deconstructing and the field, and you can test deconstruction in unit tests by deconstructing and
@ -451,8 +451,8 @@ time -- i.e., when the class is instantiated. To do that, implement
Finally, if your column requires truly complex SQL setup, return ``None`` from Finally, if your column requires truly complex SQL setup, return ``None`` from
:meth:`.db_type`. This will cause Django's SQL creation code to skip :meth:`.db_type`. This will cause Django's SQL creation code to skip
over this field. You are then responsible for creating the column in the right over this field. You are then responsible for creating the column in the right
table in some other way, of course, but this gives you a way to tell Django to table in some other way, but this gives you a way to tell Django to get out of
get out of the way. the way.
The :meth:`~Field.rel_db_type` method is called by fields such as ``ForeignKey`` The :meth:`~Field.rel_db_type` method is called by fields such as ``ForeignKey``
and ``OneToOneField`` that point to another field to determine their database and ``OneToOneField`` that point to another field to determine their database

View File

@ -21,9 +21,9 @@ manually or the :func:`post_process
<django.contrib.staticfiles.storage.StaticFilesStorage.post_process>` method of <django.contrib.staticfiles.storage.StaticFilesStorage.post_process>` method of
the ``Storage`` class might take care of that. the ``Storage`` class might take care of that.
Of course, as with all deployment tasks, the devil's in the details. Every As with all deployment tasks, the devil's in the details. Every production
production setup will be a bit different, so you'll need to adapt the basic setup will be a bit different, so you'll need to adapt the basic outline to fit
outline to fit your needs. Below are a few common patterns that might help. your needs. Below are a few common patterns that might help.
Serving the site and your static files from the same server Serving the site and your static files from the same server
----------------------------------------------------------- -----------------------------------------------------------

View File

@ -104,10 +104,9 @@ part of that. Here are some tips on how to make a request most effectively:
like to see it implemented. Include example code (non-functional is OK) like to see it implemented. Include example code (non-functional is OK)
if possible. if possible.
* Explain *why* you'd like the feature. In some cases this is obvious, but * Explain *why* you'd like the feature. Explaining a minimal use case will help
since Django is designed to help real developers get real work done, others understand where it fits in, and if there are already other ways of
you'll need to explain it, if it isn't obvious why the feature would be achieving the same thing.
useful.
If there's a consensus agreement on the feature, then it's appropriate to If there's a consensus agreement on the feature, then it's appropriate to
create a ticket. Include a link the discussion on |django-developers| in the create a ticket. Include a link the discussion on |django-developers| in the

View File

@ -32,9 +32,8 @@ translating or add a language that isn't yet translated, here's what to do:
* Then, click the "Join this Team" button to become a member of this team. * Then, click the "Join this Team" button to become a member of this team.
Every team has at least one coordinator who is responsible to review Every team has at least one coordinator who is responsible to review
your membership request. You can of course also contact the team your membership request. You can also contact the team coordinator to clarify
coordinator to clarify procedural problems and handle the actual procedural problems and handle the actual translation process.
translation process.
* Once you are a member of a team choose the translation resource you * Once you are a member of a team choose the translation resource you
want to update on the team page. For example the "core" resource refers want to update on the team page. For example the "core" resource refers

View File

@ -268,8 +268,8 @@ When a ticket has completed its useful lifecycle, it's time for it to be
closed. Closing a ticket is a big responsibility, though. You have to be sure closed. Closing a ticket is a big responsibility, though. You have to be sure
that the issue is really resolved, and you need to keep in mind that the that the issue is really resolved, and you need to keep in mind that the
reporter of the ticket may not be happy to have their ticket closed (unless reporter of the ticket may not be happy to have their ticket closed (unless
it's fixed, of course). If you're not certain about closing a ticket, leave a it's fixed!). If you're not certain about closing a ticket, leave a comment
comment with your thoughts instead. with your thoughts instead.
If you do close a ticket, you should always make sure of the following: If you do close a ticket, you should always make sure of the following:

View File

@ -82,15 +82,14 @@ As always, more communication is better than less communication!
Which tickets should be claimed? Which tickets should be claimed?
-------------------------------- --------------------------------
Of course, going through the steps of claiming tickets is overkill in some Going through the steps of claiming tickets is overkill in some cases.
cases.
In the case of small changes, such as typos in the documentation or small bugs In the case of small changes, such as typos in the documentation or small bugs
that will only take a few minutes to fix, you don't need to jump through the that will only take a few minutes to fix, you don't need to jump through the
hoops of claiming tickets. Submit your patch directly and you're done! hoops of claiming tickets. Submit your patch directly and you're done!
Of course, it is *always* acceptable, regardless whether someone has claimed it It is *always* acceptable, regardless whether someone has claimed it or not, to
or not, to submit patches to a ticket if you happen to have a patch ready. submit patches to a ticket if you happen to have a patch ready.
.. _patch-style: .. _patch-style:

View File

@ -582,9 +582,9 @@ we need to add a similar constraint to ``DetailView``:
""" """
return Question.objects.filter(pub_date__lte=timezone.now()) return Question.objects.filter(pub_date__lte=timezone.now())
And of course, we will add some tests, to check that a ``Question`` whose We should then add some tests, to check that a ``Question`` whose ``pub_date``
``pub_date`` is in the past can be displayed, and that one with a ``pub_date`` is in the past can be displayed, and that one with a ``pub_date`` in the future
in the future is not: is not:
.. code-block:: python .. code-block:: python
:caption: polls/tests.py :caption: polls/tests.py

View File

@ -112,10 +112,10 @@ loaded in the top left of the screen.
.. warning:: .. warning::
Of course the ``{% static %}`` template tag is not available for use in The ``{% static %}`` template tag is not available for use in static files
static files like your stylesheet which aren't generated by Django. You which aren't generated by Django, like your stylesheet. You should always
should always use **relative paths** to link your static files between each use **relative paths** to link your static files between each other,
other, because then you can change :setting:`STATIC_URL` (used by the because then you can change :setting:`STATIC_URL` (used by the
:ttag:`static` template tag to generate its URLs) without having to modify :ttag:`static` template tag to generate its URLs) without having to modify
a bunch of paths in your static files as well. a bunch of paths in your static files as well.

View File

@ -104,9 +104,8 @@ their :setting:`INSTALLED_APPS` setting. Besides this use case, it's best to
avoid using ``default_app_config`` and instead specify the app config class in avoid using ``default_app_config`` and instead specify the app config class in
:setting:`INSTALLED_APPS` as described next. :setting:`INSTALLED_APPS` as described next.
Of course, you can also tell your users to put You can also tell your users to put ``'rock_n_roll.apps.RockNRollConfig'`` in
``'rock_n_roll.apps.RockNRollConfig'`` in their :setting:`INSTALLED_APPS` their :setting:`INSTALLED_APPS` setting. You can even provide several different
setting. You can even provide several different
:class:`~django.apps.AppConfig` subclasses with different behaviors and allow :class:`~django.apps.AppConfig` subclasses with different behaviors and allow
your users to choose one via their :setting:`INSTALLED_APPS` setting. your users to choose one via their :setting:`INSTALLED_APPS` setting.

View File

@ -403,8 +403,8 @@ from ``TaggedItem``::
>>> TaggedItem.objects.filter(bookmark__url__contains='django') >>> TaggedItem.objects.filter(bookmark__url__contains='django')
<QuerySet [<TaggedItem: django>, <TaggedItem: python>]> <QuerySet [<TaggedItem: django>, <TaggedItem: python>]>
Of course, if you don't add the ``related_query_name``, you can do the If you don't add the ``related_query_name``, you can do the same types of
same types of lookups manually:: lookups manually::
>>> bookmarks = Bookmark.objects.filter(url__contains='django') >>> bookmarks = Bookmark.objects.filter(url__contains='django')
>>> bookmark_type = ContentType.objects.get_for_model(Bookmark) >>> bookmark_type = ContentType.objects.get_for_model(Bookmark)

View File

@ -134,8 +134,7 @@ For example::
# Do something else. # Do something else.
pass pass
Of course, it's ugly to hard-code the site IDs like that. This sort of It's fragile to hard-code the site IDs like that, in case they change. The
hard-coding is best for hackish fixes that you need done quickly. The
cleaner way of accomplishing the same thing is to check the current site's cleaner way of accomplishing the same thing is to check the current site's
domain:: domain::

View File

@ -19,8 +19,8 @@ design decisions on which features to support and which assumptions we can make
safely. safely.
This file describes some of the features that might be relevant to Django This file describes some of the features that might be relevant to Django
usage. Of course, it is not intended as a replacement for server-specific usage. It is not intended as a replacement for server-specific documentation or
documentation or reference manuals. reference manuals.
General notes General notes
============= =============

View File

@ -173,10 +173,10 @@ defaults and always applies them in the Django ORM code.
Removes a field from a model. Removes a field from a model.
Bear in mind that when reversed, this is actually adding a field to a model. Bear in mind that when reversed, this is actually adding a field to a model.
The operation is reversible (apart from any data loss, which of course is The operation is reversible (apart from any data loss, which is irreversible)
irreversible) if the field is nullable or if it has a default value that can be if the field is nullable or if it has a default value that can be used to
used to populate the recreated column. If the field is not nullable and does populate the recreated column. If the field is not nullable and does not have a
not have a default value, the operation is irreversible. default value, the operation is irreversible.
``AlterField`` ``AlterField``
-------------- --------------

View File

@ -517,8 +517,8 @@ should typically be used instead of the more verbose equivalent,
e.g. use ``TruncYear(...)`` rather than ``Trunc(..., kind='year')``. e.g. use ``TruncYear(...)`` rather than ``Trunc(..., kind='year')``.
The subclasses are all defined as transforms, but they aren't registered with The subclasses are all defined as transforms, but they aren't registered with
any fields, because the obvious lookup names are already reserved by the any fields, because the lookup names are already reserved by the ``Extract``
``Extract`` subclasses. subclasses.
Usage example:: Usage example::

View File

@ -1058,8 +1058,6 @@ directory on the filesystem. Has some special arguments, of which the first is
whether folders in the specified location should be included. Either this whether folders in the specified location should be included. Either this
or :attr:`~FilePathField.allow_files` must be ``True``. or :attr:`~FilePathField.allow_files` must be ``True``.
Of course, these arguments can be used together.
The one potential gotcha is that :attr:`~FilePathField.match` applies to the The one potential gotcha is that :attr:`~FilePathField.match` applies to the
base filename, not the full path. So, this example:: base filename, not the full path. So, this example::

View File

@ -116,8 +116,8 @@ are loaded from the database::
super().save(*args, **kwargs) super().save(*args, **kwargs)
The example above shows a full ``from_db()`` implementation to clarify how that The example above shows a full ``from_db()`` implementation to clarify how that
is done. In this case it would of course be possible to use ``super()`` call in is done. In this case it would be possible to use a ``super()`` call in the
the ``from_db()`` method. ``from_db()`` method.
Refreshing objects from database Refreshing objects from database
================================ ================================
@ -528,8 +528,8 @@ Updating attributes based on existing fields
-------------------------------------------- --------------------------------------------
Sometimes you'll need to perform a simple arithmetic task on a field, such Sometimes you'll need to perform a simple arithmetic task on a field, such
as incrementing or decrementing the current value. The obvious way to as incrementing or decrementing the current value. One way of achieving this is
achieve this is to do something like:: doing the arithmetic in Python like::
>>> product = Product.objects.get(name='Venezuelan Beaver Cheese') >>> product = Product.objects.get(name='Venezuelan Beaver Cheese')
>>> product.number_sold += 1 >>> product.number_sold += 1

View File

@ -1135,8 +1135,8 @@ This will fetch the best pizza and all the toppings for the best pizza for each
restaurant. This will be done in 3 database queries - one for the restaurants, restaurant. This will be done in 3 database queries - one for the restaurants,
one for the 'best pizzas', and one for the toppings. one for the 'best pizzas', and one for the toppings.
Of course, the ``best_pizza`` relationship could also be fetched using The ``best_pizza`` relationship could also be fetched using ``select_related``
``select_related`` to reduce the query count to 2: to reduce the query count to 2::
>>> Restaurant.objects.select_related('best_pizza').prefetch_related('best_pizza__toppings') >>> Restaurant.objects.select_related('best_pizza').prefetch_related('best_pizza__toppings')

View File

@ -643,8 +643,7 @@ of all comments related to the current task with::
{{ task.comment_set.all.count }} {{ task.comment_set.all.count }}
And of course you can easily access methods you've explicitly defined on your You can also access methods you've explicitly defined on your own models:
own models:
.. code-block:: python .. code-block:: python
:caption: models.py :caption: models.py

View File

@ -570,7 +570,7 @@ Notes:
2. In the second step you will be asked to confirm that you are prepared to 2. In the second step you will be asked to confirm that you are prepared to
lose the data for the application(s) in question. Say yes; we'll restore lose the data for the application(s) in question. Say yes; we'll restore
this data in the third step, of course. this data in the third step.
3. ``DecimalField`` is not used in any of the apps shipped with Django prior 3. ``DecimalField`` is not used in any of the apps shipped with Django prior
to this change being made, so you do not need to worry about performing to this change being made, so you do not need to worry about performing

View File

@ -88,8 +88,8 @@ Minor features
initially collapsed and their header will have a small "show" link. initially collapsed and their header will have a small "show" link.
* If a user doesn't have the add permission, the ``object-tools`` block on a * If a user doesn't have the add permission, the ``object-tools`` block on a
model's changelist will now be rendered (without the add button, of course). model's changelist will now be rendered (without the add button). This makes
This makes it easier to add custom tools in this case. it easier to add custom tools in this case.
* The :class:`~django.contrib.admin.models.LogEntry` model now stores change * The :class:`~django.contrib.admin.models.LogEntry` model now stores change
messages in a JSON structure so that the message can be dynamically translated messages in a JSON structure so that the message can be dynamically translated

View File

@ -28,11 +28,10 @@ new features from landing, including:
* Django's testing framework now supports (and ships with a copy of) * Django's testing framework now supports (and ships with a copy of)
`the unittest2 library`_. `the unittest2 library`_.
Wherever possible, of course, new features are introduced in a Wherever possible, new features are introduced in a backwards-compatible manner
backwards-compatible manner per :doc:`our API stability policy per :doc:`our API stability policy </misc/api-stability>` policy. As a result
</misc/api-stability>` policy. As a result of this policy, Django 1.3 of this policy, Django 1.3 :ref:`begins the deprecation process for some
:ref:`begins the deprecation process for some features features <deprecated-features-1.3>`.
<deprecated-features-1.3>`.
.. _using Python's logging facilities: `Logging`_ .. _using Python's logging facilities: `Logging`_
.. _easy handling of static files: `Extended static files handling`_ .. _easy handling of static files: `Extended static files handling`_

View File

@ -723,9 +723,9 @@ Released over 10 years ago, IE6 imposes many limitations on modern Web
development. The practical implications of this policy are that contributors development. The practical implications of this policy are that contributors
are free to improve the admin without consideration for these limitations. are free to improve the admin without consideration for these limitations.
Obviously, this new policy **has no impact** on sites you develop using Django. This new policy **has no impact** on sites you develop using Django. It only
It only applies to the Django admin. Feel free to develop apps compatible with applies to the Django admin. Feel free to develop apps compatible with any
any range of browsers. range of browsers.
.. _YUI's A-grade: https://github.com/yui/yui3/wiki/Graded-Browser-Support .. _YUI's A-grade: https://github.com/yui/yui3/wiki/Graded-Browser-Support
@ -1302,9 +1302,9 @@ names, like ``django.contrib.*``. The expansion was performed by a
filesystem-based implementation of ``from <package> import *``. Unfortunately, filesystem-based implementation of ``from <package> import *``. Unfortunately,
this can't be done reliably. this can't be done reliably.
This behavior was never documented. Since it is unpythonic and not obviously This behavior was never documented. Since it is unpythonic, it was removed in
useful, it was removed in Django 1.4. If you relied on it, you must edit your Django 1.4. If you relied on it, you must edit your settings file to list all
settings file to list all your applications explicitly. your applications explicitly.
``HttpRequest.raw_post_data`` renamed to ``HttpRequest.body`` ``HttpRequest.raw_post_data`` renamed to ``HttpRequest.body``
------------------------------------------------------------- -------------------------------------------------------------

View File

@ -304,9 +304,9 @@ Django 1.5 also includes several smaller improvements worth noting:
* It's not required any more to have ``404.html`` and ``500.html`` templates in * It's not required any more to have ``404.html`` and ``500.html`` templates in
the root templates directory. Django will output some basic error messages for the root templates directory. Django will output some basic error messages for
both situations when those templates are not found. Of course, it's still both situations when those templates are not found. It's still recommended as
recommended as good practice to provide those templates in order to present good practice to provide those templates in order to present pretty error
pretty error pages to the user. pages to the user.
* :mod:`django.contrib.auth` provides a new signal that is emitted * :mod:`django.contrib.auth` provides a new signal that is emitted
whenever a user fails to login successfully. See whenever a user fails to login successfully. See

View File

@ -792,7 +792,7 @@ Consequently, the expected URLs passed to ``assertRedirects`` should generally
no longer include the scheme and domain part of the URLs. For example, no longer include the scheme and domain part of the URLs. For example,
``self.assertRedirects(response, 'http://testserver/some-url/')`` should be ``self.assertRedirects(response, 'http://testserver/some-url/')`` should be
replaced by ``self.assertRedirects(response, '/some-url/')`` (unless the replaced by ``self.assertRedirects(response, '/some-url/')`` (unless the
redirection specifically contained an absolute URL, of course). redirection specifically contained an absolute URL).
In the rare case that you need the old behavior (discovered with an ancient In the rare case that you need the old behavior (discovered with an ancient
version of Apache with ``mod_scgi`` that interprets a relative redirect as an version of Apache with ``mod_scgi`` that interprets a relative redirect as an

View File

@ -257,9 +257,8 @@ operations to ``cache_replica``, and all write operations to
If you don't specify routing directions for the database cache model, If you don't specify routing directions for the database cache model,
the cache backend will use the ``default`` database. the cache backend will use the ``default`` database.
Of course, if you don't use the database cache backend, you don't need And if you don't use the database cache backend, you don't need to worry about
to worry about providing routing instructions for the database cache providing routing instructions for the database cache model.
model.
Filesystem caching Filesystem caching
------------------ ------------------
@ -325,9 +324,9 @@ order to keep them separate.
The cache uses a least-recently-used (LRU) culling strategy. The cache uses a least-recently-used (LRU) culling strategy.
Note that each process will have its own private cache instance, which means no Note that each process will have its own private cache instance, which means no
cross-process caching is possible. This obviously also means the local memory cross-process caching is possible. This also means the local memory cache isn't
cache isn't particularly memory-efficient, so it's probably not a good choice particularly memory-efficient, so it's probably not a good choice for
for production environments. It's nice for development. production environments. It's nice for development.
Dummy caching (for development) Dummy caching (for development)
------------------------------- -------------------------------

View File

@ -277,10 +277,9 @@ with the most recent first::
queryset = Book.objects.order_by('-publication_date') queryset = Book.objects.order_by('-publication_date')
context_object_name = 'book_list' context_object_name = 'book_list'
That's a pretty minimal example, but it illustrates the idea nicely. Of course, That's a pretty minimal example, but it illustrates the idea nicely. You'll
you'll usually want to do more than just reorder objects. If you want to usually want to do more than just reorder objects. If you want to present a
present a list of books by a particular publisher, you can use the same list of books by a particular publisher, you can use the same technique::
technique::
from django.views.generic import ListView from django.views.generic import ListView
from books.models import Book from books.models import Book
@ -390,9 +389,8 @@ using to keep track of the last time anybody looked at that author::
headshot = models.ImageField(upload_to='author_headshots') headshot = models.ImageField(upload_to='author_headshots')
last_accessed = models.DateTimeField() last_accessed = models.DateTimeField()
The generic ``DetailView`` class, of course, wouldn't know anything about this The generic ``DetailView`` class wouldn't know anything about this field, but
field, but once again we could easily write a custom view to keep that field once again we could write a custom view to keep that field updated.
updated.
First, we'd need to add an author detail bit in the URLconf to point to a First, we'd need to add an author detail bit in the URLconf to point to a
custom view:: custom view::

View File

@ -174,12 +174,11 @@ specialized date-based list views.)
Using Django's class-based view mixins Using Django's class-based view mixins
====================================== ======================================
Now we've seen how Django's generic class-based views use the provided Now we've seen how Django's generic class-based views use the provided mixins,
mixins, let's look at other ways we can combine them. Of course we're let's look at other ways we can combine them. We're still going to be combining
still going to be combining them with either built-in class-based them with either built-in class-based views, or other generic class-based
views, or other generic class-based views, but there are a range of views, but there are a range of rarer problems you can solve than are provided
rarer problems you can solve than are provided for by Django out of for by Django out of the box.
the box.
.. warning:: .. warning::
@ -556,7 +555,7 @@ already know that calling :meth:`~django.views.generic.base.View.as_view()` on
a class-based view gives us something that behaves exactly like a function a class-based view gives us something that behaves exactly like a function
based view, so we can do that at the point we choose between the two subviews. based view, so we can do that at the point we choose between the two subviews.
You can of course pass through keyword arguments to You can pass through keyword arguments to
:meth:`~django.views.generic.base.View.as_view()` in the same way you :meth:`~django.views.generic.base.View.as_view()` in the same way you
would in your URLconf, such as if you wanted the ``AuthorInterest`` behavior would in your URLconf, such as if you wanted the ``AuthorInterest`` behavior
to also appear at another URL but using a different template:: to also appear at another URL but using a different template::

View File

@ -126,7 +126,7 @@ You can query the models using :ref:`lookups across relationships <lookups-that-
>>> Restaurant.objects.exclude(place__address__contains="Ashland") >>> Restaurant.objects.exclude(place__address__contains="Ashland")
<QuerySet [<Restaurant: Demon Dogs the restaurant>]> <QuerySet [<Restaurant: Demon Dogs the restaurant>]>
This of course works in reverse:: This also works in reverse::
>>> Place.objects.get(pk=1) >>> Place.objects.get(pk=1)
<Place: Demon Dogs the place> <Place: Demon Dogs the place>

View File

@ -135,9 +135,9 @@ With this sample model, ``Book.objects.all()`` will return all books in the
database, but ``Book.dahl_objects.all()`` will only return the ones written by database, but ``Book.dahl_objects.all()`` will only return the ones written by
Roald Dahl. Roald Dahl.
Of course, because ``get_queryset()`` returns a ``QuerySet`` object, you can Because ``get_queryset()`` returns a ``QuerySet`` object, you can use
use ``filter()``, ``exclude()`` and all the other ``QuerySet`` methods on it. ``filter()``, ``exclude()`` and all the other ``QuerySet`` methods on it. So
So these statements are all legal:: these statements are all legal::
Book.dahl_objects.all() Book.dahl_objects.all()
Book.dahl_objects.filter(title='Matilda') Book.dahl_objects.filter(title='Matilda')

View File

@ -352,8 +352,8 @@ reference <ref-foreignkey>` for details.
It's suggested, but not required, that the name of a It's suggested, but not required, that the name of a
:class:`~django.db.models.ForeignKey` field (``manufacturer`` in the example :class:`~django.db.models.ForeignKey` field (``manufacturer`` in the example
above) be the name of the model, lowercase. You can, of course, call the field above) be the name of the model, lowercase. You can call the field whatever you
whatever you want. For example:: want. For example::
class Car(models.Model): class Car(models.Model):
company_that_makes_it = models.ForeignKey( company_that_makes_it = models.ForeignKey(
@ -952,12 +952,12 @@ extend the parent's :ref:`Meta <meta-options>` class, it can subclass it. For ex
class Meta(CommonInfo.Meta): class Meta(CommonInfo.Meta):
db_table = 'student_info' db_table = 'student_info'
Django does make one adjustment to the :ref:`Meta <meta-options>` class of an abstract base Django does make one adjustment to the :ref:`Meta <meta-options>` class of an
class: before installing the :ref:`Meta <meta-options>` attribute, it sets ``abstract=False``. abstract base class: before installing the :ref:`Meta <meta-options>`
This means that children of abstract base classes don't automatically become attribute, it sets ``abstract=False``. This means that children of abstract
abstract classes themselves. Of course, you can make an abstract base class base classes don't automatically become abstract classes themselves. To make
that inherits from another abstract base class. You just need to remember to an abstract base class that inherits from another abstract base class, you need
explicitly set ``abstract=True`` each time. to explicitly set ``abstract=True`` on the child.
Some attributes won't make sense to include in the :ref:`Meta <meta-options>` class of an Some attributes won't make sense to include in the :ref:`Meta <meta-options>` class of an
abstract base class. For example, including ``db_table`` would mean that all abstract base class. For example, including ``db_table`` would mean that all

View File

@ -1201,8 +1201,8 @@ query you can use the following syntax::
If ``EntryManager`` performed default filtering in its ``get_queryset()`` If ``EntryManager`` performed default filtering in its ``get_queryset()``
method, that filtering would apply to the ``all()`` call. method, that filtering would apply to the ``all()`` call.
Of course, specifying a custom reverse manager also enables you to call its Specifying a custom reverse manager also enables you to call its custom
custom methods:: methods::
b.entry_set(manager='entries').is_published() b.entry_set(manager='entries').is_published()

View File

@ -64,9 +64,9 @@ You could then execute custom SQL like so::
John Smith John Smith
Jane Jones Jane Jones
Of course, this example isn't very exciting -- it's exactly the same as This example isn't very exciting -- it's exactly the same as running
running ``Person.objects.all()``. However, ``raw()`` has a bunch of other ``Person.objects.all()``. However, ``raw()`` has a bunch of other options that
options that make it very powerful. make it very powerful.
.. admonition:: Model table names .. admonition:: Model table names
@ -206,9 +206,8 @@ argument to ``raw()``::
``params`` is a list or dictionary of parameters. You'll use ``%s`` ``params`` is a list or dictionary of parameters. You'll use ``%s``
placeholders in the query string for a list, or ``%(key)s`` placeholders in the query string for a list, or ``%(key)s``
placeholders for a dictionary (where ``key`` is replaced by a placeholders for a dictionary (where ``key`` is replaced by a
dictionary key, of course), regardless of your database engine. Such dictionary key), regardless of your database engine. Such placeholders will be
placeholders will be replaced with parameters from the ``params`` replaced with parameters from the ``params`` argument.
argument.
.. note:: .. note::

View File

@ -355,8 +355,8 @@ Exception handling
If one on-commit function within a given transaction raises an uncaught If one on-commit function within a given transaction raises an uncaught
exception, no later registered functions in that same transaction will run. exception, no later registered functions in that same transaction will run.
This is, of course, the same behavior as if you'd executed the functions This is the same behavior as if you'd executed the functions sequentially
sequentially yourself without :func:`on_commit`. yourself without :func:`on_commit`.
Timing of execution Timing of execution
------------------- -------------------

View File

@ -576,11 +576,11 @@ Complete ``<label>`` elements can also be generated using the
Rendering form error messages Rendering form error messages
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Of course, the price of this flexibility is more work. Until now we haven't had The price of this flexibility is a bit more work. Until now we haven't had to
to worry about how to display form errors, because that's taken care of for us. worry about how to display form errors, because that's taken care of for us. In
In this example we have had to make sure we take care of any errors for each this example we have had to make sure we take care of any errors for each field
field and any errors for the form as a whole. Note ``{{ form.non_field_errors and any errors for the form as a whole. Note ``{{ form.non_field_errors }}`` at
}}`` at the top of the form and the template lookup for errors on each field. the top of the form and the template lookup for errors on each field.
Using ``{{ form.name_of_field.errors }}`` displays a list of form errors, Using ``{{ form.name_of_field.errors }}`` displays a list of form errors,
rendered as an unordered list. This might look like: rendered as an unordered list. This might look like:

View File

@ -197,9 +197,9 @@ There are two other logging calls available:
Configuring logging Configuring logging
=================== ===================
Of course, it isn't enough to just put logging calls into your code. It isn't enough to just put logging calls into your code. You also need to
You also need to configure the loggers, handlers, filters and configure the loggers, handlers, filters, and formatters to ensure you can use
formatters to ensure that logging output is output in a useful way. the logging output.
Python's logging library provides several techniques to configure Python's logging library provides several techniques to configure
logging, ranging from a programmatic interface to configuration files. logging, ranging from a programmatic interface to configuration files.

View File

@ -135,8 +135,8 @@ something like::
deserialized_object.save() deserialized_object.save()
In other words, the usual use is to examine the deserialized objects to make In other words, the usual use is to examine the deserialized objects to make
sure that they are "appropriate" for saving before doing so. Of course, if you sure that they are "appropriate" for saving before doing so. If you trust your
trust your data source you can instead save the object directly and move on. data source you can instead save the object directly and move on.
The Django object itself can be inspected as ``deserialized_object.object``. The Django object itself can be inspected as ``deserialized_object.object``.
If fields in the serialized data do not exist on a model, a If fields in the serialized data do not exist on a model, a

View File

@ -191,8 +191,8 @@ class CustomPKTests(TestCase):
Business.objects.create(name='jaźń') Business.objects.create(name='jaźń')
def test_unique_pk(self): def test_unique_pk(self):
# The primary key must also obviously be unique, so trying to create a # The primary key must also be unique, so trying to create a new object
# new object with the same primary key will fail. # with the same primary key will fail.
Employee.objects.create( Employee.objects.create(
employee_code=123, first_name="Frank", last_name="Jones" employee_code=123, first_name="Frank", last_name="Jones"
) )

View File

@ -60,10 +60,6 @@ class SelectRelatedTests(TestCase):
self.assertEqual(domain.name, 'Eukaryota') self.assertEqual(domain.name, 'Eukaryota')
def test_list_without_select_related(self): def test_list_without_select_related(self):
"""
select_related() also of course applies to entire lists, not just
items. This test verifies the expected behavior without select_related.
"""
with self.assertNumQueries(9): with self.assertNumQueries(9):
world = Species.objects.all() world = Species.objects.all()
families = [o.genus.family.name for o in world] families = [o.genus.family.name for o in world]
@ -75,10 +71,7 @@ class SelectRelatedTests(TestCase):
]) ])
def test_list_with_select_related(self): def test_list_with_select_related(self):
""" """select_related() applies to entire lists, not just items."""
select_related() also of course applies to entire lists, not just
items. This test verifies the expected behavior with select_related.
"""
with self.assertNumQueries(1): with self.assertNumQueries(1):
world = Species.objects.all().select_related() world = Species.objects.all().select_related()
families = [o.genus.family.name for o in world] families = [o.genus.family.name for o in world]

View File

@ -1060,14 +1060,14 @@ class LegacyFormsTests(TestCase):
def test_form_with_non_existent_time(self): def test_form_with_non_existent_time(self):
form = EventForm({'dt': '2011-03-27 02:30:00'}) form = EventForm({'dt': '2011-03-27 02:30:00'})
with timezone.override(pytz.timezone('Europe/Paris')): with timezone.override(pytz.timezone('Europe/Paris')):
# this is obviously a bug # This is a bug.
self.assertTrue(form.is_valid()) self.assertTrue(form.is_valid())
self.assertEqual(form.cleaned_data['dt'], datetime.datetime(2011, 3, 27, 2, 30, 0)) self.assertEqual(form.cleaned_data['dt'], datetime.datetime(2011, 3, 27, 2, 30, 0))
def test_form_with_ambiguous_time(self): def test_form_with_ambiguous_time(self):
form = EventForm({'dt': '2011-10-30 02:30:00'}) form = EventForm({'dt': '2011-10-30 02:30:00'})
with timezone.override(pytz.timezone('Europe/Paris')): with timezone.override(pytz.timezone('Europe/Paris')):
# this is obviously a bug # This is a bug.
self.assertTrue(form.is_valid()) self.assertTrue(form.is_valid())
self.assertEqual(form.cleaned_data['dt'], datetime.datetime(2011, 10, 30, 2, 30, 0)) self.assertEqual(form.cleaned_data['dt'], datetime.datetime(2011, 10, 30, 2, 30, 0))

View File

@ -7,8 +7,8 @@ from django.utils.safestring import SafeData, mark_safe
class customescape(str): class customescape(str):
def __html__(self): def __html__(self):
# implement specific and obviously wrong escaping # Implement specific and wrong escaping in order to be able to detect
# in order to be able to tell for sure when it runs # when it runs.
return self.replace('<', '<<').replace('>', '>>') return self.replace('<', '<<').replace('>', '>>')