diff options
| author | Andrew Godwin <andrew@aeracode.org> | 2012-07-26 18:58:10 +0100 |
|---|---|---|
| committer | Andrew Godwin <andrew@aeracode.org> | 2012-07-26 18:58:10 +0100 |
| commit | 4a2e80fff44d0eb1856b593ac5f31ab1492b3e45 (patch) | |
| tree | 9bc87a682dc488e6555792c1d4bb53f5f3cdc880 /docs | |
| parent | 959a3f9791d780062c4efe8765404a8ef95e87f0 (diff) | |
| parent | ab6cd1c839b136cbc94178da433b2e97ab7f6061 (diff) | |
Merge branch 'master' of github.com:django/django into schema-alteration
Conflicts:
django/db/backends/postgresql_psycopg2/base.py
Diffstat (limited to 'docs')
72 files changed, 745 insertions, 584 deletions
diff --git a/docs/conf.py b/docs/conf.py index 659115dfbd..39a280e464 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -94,6 +94,7 @@ pygments_style = 'trac' intersphinx_mapping = { 'python': ('http://docs.python.org/2.7', None), 'sphinx': ('http://sphinx.pocoo.org/', None), + 'six': ('http://packages.python.org/six/', None), } # Python's docs don't change every week. diff --git a/docs/faq/install.txt b/docs/faq/install.txt index e2ecfb4717..a14615e47c 100644 --- a/docs/faq/install.txt +++ b/docs/faq/install.txt @@ -16,8 +16,8 @@ How do I get started? What are Django's prerequisites? -------------------------------- -Django requires Python_, specifically Python 2.6 or 2.7. -No other Python libraries are required for basic Django usage. +Django requires Python_, specifically Python 2.6.5 - 2.7.x. No other Python +libraries are required for basic Django usage. For a development environment -- if you just want to experiment with Django -- you don't need to have a separate Web server installed; Django comes with its @@ -42,7 +42,7 @@ Do I lose anything by using Python 2.6 versus newer Python versions, such as Pyt ---------------------------------------------------------------------------------------- Not in the core framework. Currently, Django itself officially supports -Python 2.6 and 2.7. However, newer versions of +Python 2.6 (2.6.5 or higher) and 2.7. However, newer versions of Python are often faster, have more features, and are better supported. If you use a newer version of Python you will also have access to some APIs that aren't available under older versions of Python. diff --git a/docs/faq/models.txt b/docs/faq/models.txt index d34a26a82e..4a83aa9f2c 100644 --- a/docs/faq/models.txt +++ b/docs/faq/models.txt @@ -40,18 +40,15 @@ Yes. See :doc:`Integrating with a legacy database </howto/legacy-databases>`. If I make changes to a model, how do I update the database? ----------------------------------------------------------- -If you don't mind clearing data, your project's ``manage.py`` utility has an -option to reset the SQL for a particular application:: - - manage.py reset appname - -This drops any tables associated with ``appname`` and recreates them. +If you don't mind clearing data, your project's ``manage.py`` utility has a +:djadmin:`flush` option to reset the database to the state it was in +immediately after :djadmin:`syncdb` was executed. If you do care about deleting data, you'll have to execute the ``ALTER TABLE`` statements manually in your database. There are `external projects which handle schema updates -<http://djangopackages.com/grids/g/database-migration/>`_, of which the current +<http://www.djangopackages.com/grids/g/database-migration/>`_, of which the current defacto standard is `south <http://south.aeracode.org/>`_. Do Django models support multiple-column primary keys? diff --git a/docs/howto/custom-management-commands.txt b/docs/howto/custom-management-commands.txt index 4a27bdf7a9..12e8ec2494 100644 --- a/docs/howto/custom-management-commands.txt +++ b/docs/howto/custom-management-commands.txt @@ -129,7 +129,7 @@ default options such as :djadminopt:`--verbosity` and :djadminopt:`--traceback`. class Command(BaseCommand): ... - self.can_import_settings = True + can_import_settings = True def handle(self, *args, **options): diff --git a/docs/howto/custom-model-fields.txt b/docs/howto/custom-model-fields.txt index 1377a62c89..706cc25129 100644 --- a/docs/howto/custom-model-fields.txt +++ b/docs/howto/custom-model-fields.txt @@ -434,10 +434,14 @@ database, so we need to be able to process strings and ``Hand`` instances in p1 = re.compile('.{26}') p2 = re.compile('..') args = [p2.findall(x) for x in p1.findall(value)] + if len(args) != 4: + raise ValidationError("Invalid input for a Hand instance") return Hand(*args) Notice that we always return a ``Hand`` instance from this method. That's the -Python object type we want to store in the model's attribute. +Python object type we want to store in the model's attribute. If anything is +going wrong during value conversion, you should raise a +:exc:`~django.core.exceptions.ValidationError` exception. **Remember:** If your custom field needs the :meth:`to_python` method to be called when it is created, you should be using `The SubfieldBase metaclass`_ @@ -666,7 +670,7 @@ data storage anyway, we can reuse some existing conversion code:: def value_to_string(self, obj): value = self._get_val_from_obj(obj) - return self.get_db_prep_value(value) + return self.get_prep_value(value) Some general advice -------------------- diff --git a/docs/howto/deployment/wsgi/uwsgi.txt b/docs/howto/deployment/wsgi/uwsgi.txt index 3ac2203544..b5d438450e 100644 --- a/docs/howto/deployment/wsgi/uwsgi.txt +++ b/docs/howto/deployment/wsgi/uwsgi.txt @@ -46,7 +46,7 @@ uWSGI supports multiple ways to configure the process. See uWSGI's Here's an example command to start a uWSGI server:: - uwsgi --chdir=/path/to/your/project + uwsgi --chdir=/path/to/your/project \ --module=mysite.wsgi:application \ --env DJANGO_SETTINGS_MODULE=mysite.settings \ --master --pidfile=/tmp/project-master.pid \ diff --git a/docs/howto/initial-data.txt b/docs/howto/initial-data.txt index e5a4957cb2..eca2e2c4f9 100644 --- a/docs/howto/initial-data.txt +++ b/docs/howto/initial-data.txt @@ -67,12 +67,12 @@ And here's that same fixture as YAML: You'll store this data in a ``fixtures`` directory inside your app. -Loading data is easy: just call :djadmin:`manage.py loaddata <fixturename> -<loaddata>`, where ``<fixturename>`` is the name of the fixture file you've -created. Each time you run :djadmin:`loaddata`, the data will be read from the -fixture and re-loaded into the database. Note this means that if you change one -of the rows created by a fixture and then run :djadmin:`loaddata` again, you'll -wipe out any changes you've made. +Loading data is easy: just call :djadmin:`manage.py loaddata <loaddata>` +``<fixturename>``, where ``<fixturename>`` is the name of the fixture file +you've created. Each time you run :djadmin:`loaddata`, the data will be read +from the fixture and re-loaded into the database. Note this means that if you +change one of the rows created by a fixture and then run :djadmin:`loaddata` +again, you'll wipe out any changes you've made. Automatically loading initial data fixtures ------------------------------------------- diff --git a/docs/howto/jython.txt b/docs/howto/jython.txt index 2cee4e6daa..762250212a 100644 --- a/docs/howto/jython.txt +++ b/docs/howto/jython.txt @@ -36,7 +36,7 @@ such as `Apache Tomcat`_. Full JavaEE applications servers such as `GlassFish`_ or `JBoss`_ are also OK, if you need the extra features they include. .. _`Apache Tomcat`: http://tomcat.apache.org/ -.. _GlassFish: https://glassfish.dev.java.net/ +.. _GlassFish: http://glassfish.java.net/ .. _JBoss: http://www.jboss.org/ Installing Django diff --git a/docs/internals/committers.txt b/docs/internals/committers.txt index 972e506155..fb601a24c0 100644 --- a/docs/internals/committers.txt +++ b/docs/internals/committers.txt @@ -146,7 +146,7 @@ Joseph Kocherhans Brian lives in Denver, Colorado, USA. -.. _brian rosner: http://oebfare.com/ +.. _brian rosner: http://brosner.com/ .. _eldarion: http://eldarion.com/ .. _django dose: http://djangodose.com/ @@ -162,7 +162,7 @@ Joseph Kocherhans Gary lives in Austin, Texas, USA. -.. _Gary Wilson: http://gdub.wordpress.com/ +.. _Gary Wilson: http://thegarywilson.com/ .. _The University of Texas: http://www.utexas.edu/ Justin Bronn @@ -191,14 +191,19 @@ Karen Tracey `Jannis Leidel`_ Jannis graduated in media design from `Bauhaus-University Weimar`_, is the author of a number of pluggable Django apps and likes to - contribute to Open Source projects like Pinax_. He currently works as - a freelance Web developer and designer. + contribute to Open Source projects like virtualenv_ and pip_. + + He has worked on Django's auth, admin and staticfiles apps as well as + the form, core, internationalization and test systems. He currently works + as the lead engineer at Gidsy_. Jannis lives in Berlin, Germany. .. _Jannis Leidel: http://jezdez.com/ .. _Bauhaus-University Weimar: http://www.uni-weimar.de/ -.. _pinax: http://pinaxproject.com/ +.. _virtualenv: http://www.virtualenv.org/ +.. _pip: http://www.pip-installer.org/ +.. _Gidsy: http://gidsy.com/ `James Tauber`_ James is the lead developer of Pinax_ and the CEO and founder of @@ -214,15 +219,15 @@ Karen Tracey .. _James Tauber: http://jtauber.com/ `Alex Gaynor`_ - Alex is a student at Rensselaer Polytechnic Institute, and is also an - independent contractor. He found Django in 2007 and has been addicted ever - since he found out you don't need to write out your forms by hand. He has - a small obsession with compilers. He's contributed to the ORM, forms, - admin, and other components of Django. + Alex is a software engineer working at Rdio_. He found Django in 2007 and + has been addicted ever since he found out you don't need to write out your + forms by hand. He has a small obsession with compilers. He's contributed + to the ORM, forms, admin, and other components of Django. - Alex lives in Chicago, IL, but spends most of his time in Troy, NY. + Alex lives in San Francisco, CA, USA. .. _Alex Gaynor: http://alexgaynor.net +.. _Rdio: http://rdio.com `Andrew Godwin`_ Andrew is a freelance Python developer and tinkerer, and has been @@ -365,6 +370,16 @@ Anssi Kääriäinen all related features. He's also a fan of benckmarking and he tries keep Django as fast as possible. +Florian Apolloner + Florian is currently studying Physics at the `Graz University of Technology`_. + Soon after he started using Django he joined the `Ubuntuusers webteam`_ to + work on *Inyoka*, the software powering the whole Ubuntusers site. + + For the time beeing he lives in Graz, Austria (not Australia ;)). + +.. _Graz University of Technology: http://tugraz.at/ +.. _Ubuntuusers webteam: http://wiki.ubuntuusers.de/ubuntuusers/Webteam + Specialists ----------- diff --git a/docs/internals/contributing/localizing.txt b/docs/internals/contributing/localizing.txt index ff957c44a4..263087b5fa 100644 --- a/docs/internals/contributing/localizing.txt +++ b/docs/internals/contributing/localizing.txt @@ -60,7 +60,7 @@ Django source tree, as for any code change: * Open a ticket in Django's ticket system, set its ``Component`` field to ``Translations``, and attach the patch to it. -.. _Transifex: https://www.transifex.net/ +.. _Transifex: https://www.transifex.com/ .. _Django i18n mailing list: http://groups.google.com/group/django-i18n/ -.. _Django project page: https://www.transifex.net/projects/p/django/ -.. _Transifex User Guide: http://help.transifex.net/ +.. _Django project page: https://www.transifex.com/projects/p/django/ +.. _Transifex User Guide: http://help.transifex.com/ diff --git a/docs/internals/contributing/writing-code/unit-tests.txt b/docs/internals/contributing/writing-code/unit-tests.txt index 9d6e76e453..4de506a654 100644 --- a/docs/internals/contributing/writing-code/unit-tests.txt +++ b/docs/internals/contributing/writing-code/unit-tests.txt @@ -159,7 +159,7 @@ associated tests will be skipped. .. _Textile: http://pypi.python.org/pypi/textile .. _docutils: http://pypi.python.org/pypi/docutils/0.4 .. _setuptools: http://pypi.python.org/pypi/setuptools/ -.. _memcached: http://www.danga.com/memcached/ +.. _memcached: http://memcached.org/ .. _gettext: http://www.gnu.org/software/gettext/manual/gettext.html .. _selenium: http://pypi.python.org/pypi/selenium diff --git a/docs/internals/contributing/writing-documentation.txt b/docs/internals/contributing/writing-documentation.txt index e91d1291e9..c8d7039a68 100644 --- a/docs/internals/contributing/writing-documentation.txt +++ b/docs/internals/contributing/writing-documentation.txt @@ -22,7 +22,7 @@ Getting the raw documentation ----------------------------- Though Django's documentation is intended to be read as HTML at -http://docs.djangoproject.com/, we edit it as a collection of text files for +https://docs.djangoproject.com/, we edit it as a collection of text files for maximum flexibility. These files live in the top-level ``docs/`` directory of a Django release. diff --git a/docs/internals/deprecation.txt b/docs/internals/deprecation.txt index 342ef5266a..9359c82e46 100644 --- a/docs/internals/deprecation.txt +++ b/docs/internals/deprecation.txt @@ -276,6 +276,13 @@ these changes. * The function ``django.utils.itercompat.product`` will be removed. The Python builtin version should be used instead. +* Auto-correction of INSTALLED_APPS and TEMPLATE_DIRS settings when they are + specified as a plain string instead of a tuple will be removed and raise an + exception. + +* The ``mimetype`` argument to :class:`~django.http.HttpResponse` ``__init__`` + will be removed (``content_type`` should be used instead). + 2.0 --- diff --git a/docs/intro/_images/admin12t.png b/docs/intro/_images/admin12t.png Binary files differnew file mode 100644 index 0000000000..14c5c31a4f --- /dev/null +++ b/docs/intro/_images/admin12t.png diff --git a/docs/intro/install.txt b/docs/intro/install.txt index 41339b5f11..7e8c7db7b3 100644 --- a/docs/intro/install.txt +++ b/docs/intro/install.txt @@ -10,7 +10,7 @@ Install Python -------------- Being a Python Web framework, Django requires Python. It works with any Python -version from 2.6 to 2.7 (due to backwards incompatibilities in Python 3.0, +version from 2.6.5 to 2.7 (due to backwards incompatibilities in Python 3.0, Django does not currently work with Python 3.0; see :doc:`the Django FAQ </faq/install>` for more information on supported Python versions and the 3.0 transition), these versions of Python include a lightweight database called diff --git a/docs/intro/tutorial02.txt b/docs/intro/tutorial02.txt index 0d95f6ff37..84da36be86 100644 --- a/docs/intro/tutorial02.txt +++ b/docs/intro/tutorial02.txt @@ -113,8 +113,8 @@ Just one thing to do: We need to tell the admin that ``Poll`` objects have an admin interface. To do this, create a file called ``admin.py`` in your ``polls`` directory, and edit it to look like this:: - from polls.models import Poll from django.contrib import admin + from polls.models import Poll admin.site.register(Poll) @@ -283,6 +283,9 @@ It'd be better if you could add a bunch of Choices directly when you create the Remove the ``register()`` call for the ``Choice`` model. Then, edit the ``Poll`` registration code to read:: + from django.contrib import admin + from polls.models import Choice, Poll + class ChoiceInline(admin.StackedInline): model = Choice extra = 3 @@ -319,9 +322,12 @@ the ``ChoiceInline`` declaration to read:: With that ``TabularInline`` (instead of ``StackedInline``), the related objects are displayed in a more compact, table-based format: -.. image:: _images/admin12.png +.. image:: _images/admin12t.png :alt: Add poll page now has more compact choices +Note that there is an extra "Delete?" column that allows removing rows added +using the "Add Another Choice" button and rows that have already been saved. + Customize the admin change list =============================== @@ -442,6 +448,19 @@ above, then copy ``django/contrib/admin/templates/admin/base_site.html`` to ``/home/my_username/mytemplates/admin/base_site.html``. Don't forget that ``admin`` subdirectory. +.. admonition:: Where are the Django source files? + + If you have difficulty finding where the Django source files are located + on your system, run the following command: + + .. code-block:: bash + + python -c " + import sys + sys.path = sys.path[1:] + import django + print(django.__path__)" + Then, just edit the file and replace the generic Django text with your own site's name as you see fit. diff --git a/docs/intro/whatsnext.txt b/docs/intro/whatsnext.txt index 6e0d97fefd..cc793c8129 100644 --- a/docs/intro/whatsnext.txt +++ b/docs/intro/whatsnext.txt @@ -108,7 +108,7 @@ On the Web ---------- The most recent version of the Django documentation lives at -http://docs.djangoproject.com/en/dev/. These HTML pages are generated +https://docs.djangoproject.com/en/dev/. These HTML pages are generated automatically from the text files in source control. That means they reflect the "latest and greatest" in Django -- they include the very latest corrections and additions, and they discuss the latest Django features, which may only be @@ -124,7 +124,7 @@ rather than asking broad tech-support questions. If you need help with your particular Django setup, try the `django-users mailing list`_ or the `#django IRC channel`_ instead. -.. _ticket system: https://code.djangoproject.com/simpleticket?component=Documentation +.. _ticket system: https://code.djangoproject.com/newticket?component=Documentation .. _django-users mailing list: http://groups.google.com/group/django-users .. _#django IRC channel: irc://irc.freenode.net/django @@ -228,4 +228,4 @@ We follow this policy: * The `main documentation Web page`_ includes links to documentation for all previous versions. -.. _main documentation Web page: http://docs.djangoproject.com/en/dev/ +.. _main documentation Web page: https://docs.djangoproject.com/en/dev/ diff --git a/docs/ref/class-based-views/generic-display.txt b/docs/ref/class-based-views/generic-display.txt index 8ec66a8cc1..bbf0d4f05a 100644 --- a/docs/ref/class-based-views/generic-display.txt +++ b/docs/ref/class-based-views/generic-display.txt @@ -54,7 +54,7 @@ many projects they are typically the most commonly used views. from article.views import ArticleDetailView urlpatterns = patterns('', - url(r'^(?P<slug>[-_\w]+)/$', ArticleDetailView.as_view(), 'article-detail'), + url(r'^(?P<slug>[-_\w]+)/$', ArticleDetailView.as_view(), name='article-detail'), ) .. class:: django.views.generic.list.ListView @@ -76,11 +76,11 @@ many projects they are typically the most commonly used views. **Method Flowchart** - 1. :meth:`dispatch():` - 2. :meth:`http_method_not_allowed():` - 3. :meth:`get_template_names():` - 4. :meth:`get_queryset():` - 5. :meth:`get_objects():` - 6. :meth:`get_context_data():` - 7. :meth:`get():` - 8. :meth:`render_to_response():` + 1. :meth:`dispatch()` + 2. :meth:`http_method_not_allowed()` + 3. :meth:`get_template_names()` + 4. :meth:`get_queryset()` + 5. :meth:`get_objects()` + 6. :meth:`get_context_data()` + 7. :meth:`get()` + 8. :meth:`render_to_response()` diff --git a/docs/ref/contrib/admin/index.txt b/docs/ref/contrib/admin/index.txt index 3ef9abe6da..f28aa4687b 100644 --- a/docs/ref/contrib/admin/index.txt +++ b/docs/ref/contrib/admin/index.txt @@ -115,7 +115,7 @@ subclass:: .. attribute:: ModelAdmin.actions_selection_counter - Controls whether a selection counter is display next to the action dropdown. + Controls whether a selection counter is displayed next to the action dropdown. By default, the admin changelist will display it (``actions_selection_counter = True``). @@ -371,12 +371,6 @@ subclass:: because ``raw_id_fields`` and ``radio_fields`` imply custom widgets of their own. -.. attribute:: ModelAdmin.get_changelist - - Returns the Changelist class to be used for listing. By default, - ``django.contrib.admin.views.main.ChangeList`` is used. By inheriting this - class you can change the behavior of the listing. - .. attribute:: ModelAdmin.inlines See :class:`InlineModelAdmin` objects below. @@ -1168,6 +1162,12 @@ templates used by the :class:`ModelAdmin` views: kwargs['choices'] += (('ready', 'Ready for deployment'),) return super(MyModelAdmin, self).formfield_for_choice_field(db_field, request, **kwargs) +.. method:: ModelAdmin.get_changelist(self, request, **kwargs) + + Returns the Changelist class to be used for listing. By default, + ``django.contrib.admin.views.main.ChangeList`` is used. By inheriting this + class you can change the behavior of the listing. + .. method:: ModelAdmin.has_add_permission(self, request) Should return ``True`` if adding an object is permitted, ``False`` @@ -1948,16 +1948,17 @@ accessible using Django's :ref:`URL reversing system <naming-url-patterns>`. The :class:`AdminSite` provides the following named URL patterns: -====================== ======================== ============= -Page URL name Parameters -====================== ======================== ============= -Index ``index`` -Logout ``logout`` -Password change ``password_change`` -Password change done ``password_change_done`` -i18n javascript ``jsi18n`` -Application index page ``app_list`` ``app_label`` -====================== ======================== ============= +========================= ======================== ================================== +Page URL name Parameters +========================= ======================== ================================== +Index ``index`` +Logout ``logout`` +Password change ``password_change`` +Password change done ``password_change_done`` +i18n javascript ``jsi18n`` +Application index page ``app_list`` ``app_label`` +Redirect to object's page ``view_on_site`` ``content_type_id``, ``object_id`` +========================= ======================== ================================== Each :class:`ModelAdmin` instance provides an additional set of named URLs: diff --git a/docs/ref/contrib/comments/index.txt b/docs/ref/contrib/comments/index.txt index 40b1b662b7..af937e036e 100644 --- a/docs/ref/contrib/comments/index.txt +++ b/docs/ref/contrib/comments/index.txt @@ -250,7 +250,7 @@ Redirecting after the comment post To specify the URL you want to redirect to after the comment has been posted, you can include a hidden form input called ``next`` in your comment form. For example:: - <input type="hidden" name="next" value="{% url my_comment_was_posted %}" /> + <input type="hidden" name="next" value="{% url 'my_comment_was_posted' %}" /> .. _notes-on-the-comment-form: diff --git a/docs/ref/contrib/formtools/form-wizard.txt b/docs/ref/contrib/formtools/form-wizard.txt index 7aafbe89f3..7d229a5d66 100644 --- a/docs/ref/contrib/formtools/form-wizard.txt +++ b/docs/ref/contrib/formtools/form-wizard.txt @@ -554,9 +554,8 @@ How to work with ModelForm and ModelFormSet WizardView supports :doc:`ModelForms </topics/forms/modelforms>` and :ref:`ModelFormSets <model-formsets>`. Additionally to :attr:`~WizardView.initial_dict`, the :meth:`~WizardView.as_view` method takes -an ``instance_dict`` argument that should contain instances of ``ModelForm`` and -``ModelFormSet``. Similarly to :attr:`~WizardView.initial_dict`, these -dictionary key values should be equal to the step number in the form list. +an ``instance_dict`` argument that should contain model instances for steps +based on ``ModelForm`` and querysets for steps based on ``ModelFormSet``. Usage of ``NamedUrlWizardView`` =============================== diff --git a/docs/ref/contrib/gis/deployment.txt b/docs/ref/contrib/gis/deployment.txt index d98fc51837..f90c9c2e91 100644 --- a/docs/ref/contrib/gis/deployment.txt +++ b/docs/ref/contrib/gis/deployment.txt @@ -2,6 +2,10 @@ Deploying GeoDjango =================== +Basically, the deployment of a GeoDjango application is not different from +the deployment of a normal Django application. Please consult Django's +:doc:`deployment documentation </howto/deployment/index>`. + .. warning:: GeoDjango uses the GDAL geospatial library which is @@ -10,58 +14,7 @@ Deploying GeoDjango appropriate configuration of Apache or the prefork method when using FastCGI through another Web server. -Apache -====== -In this section there are some example ``VirtualHost`` directives for -when deploying using ``mod_wsgi``, which is now officially the recommended -way to deploy Django applications with Apache. -As long as ``mod_wsgi`` is configured correctly, it does not -matter whether the version of Apache is prefork or worker. - -.. note:: - - The ``Alias`` and ``Directory`` configurations in the examples - below use an example path to a system-wide installation folder of Django. - Substitute in an appropriate location, if necessary, as it may be - different than the path on your system. - -``mod_wsgi`` ------------- - -Example:: - - <VirtualHost *:80> - WSGIDaemonProcess geodjango user=geo group=geo processes=5 threads=1 - WSGIProcessGroup geodjango - WSGIScriptAlias / /home/geo/geodjango/world.wsgi - - Alias /media/ "/usr/lib/python2.6/site-packages/django/contrib/admin/media/" - <Directory "/usr/lib/python2.6/site-packages/django/contrib/admin/media/"> - Order allow,deny - Options Indexes - Allow from all - IndexOptions FancyIndexing - </Directory> - - </VirtualHost> - -.. warning:: - - If the ``WSGIDaemonProcess`` attribute ``threads`` is not set to ``1``, then + For example, when configuring your application with ``mod_wsgi``, + set the ``WSGIDaemonProcess`` attribute ``threads`` to ``1``, unless Apache may crash when running your GeoDjango application. Increase the number of ``processes`` instead. - -For more information, please consult Django's -:doc:`mod_wsgi documentation </howto/deployment/wsgi/modwsgi>`. - -Lighttpd -======== - -FastCGI -------- - -Nginx -===== - -FastCGI -------- diff --git a/docs/ref/contrib/gis/gdal.txt b/docs/ref/contrib/gis/gdal.txt index 619f23fba2..c4b29bead7 100644 --- a/docs/ref/contrib/gis/gdal.txt +++ b/docs/ref/contrib/gis/gdal.txt @@ -447,7 +447,7 @@ systems and coordinate transformation:: This object is a wrapper for the `OGR Geometry`__ class. These objects are instantiated directly from the given ``geom_input`` - parameter, which may be a string containing WKT or HEX, a ``buffer`` + parameter, which may be a string containing WKT, HEX, GeoJSON, a ``buffer`` containing WKB data, or an :class:`OGRGeomType` object. These objects are also returned from the :class:`Feature.geom` attribute, when reading vector data from :class:`Layer` (which is in turn a part of diff --git a/docs/ref/contrib/gis/geoquerysets.txt b/docs/ref/contrib/gis/geoquerysets.txt index da00aa97f8..eeec2e2133 100644 --- a/docs/ref/contrib/gis/geoquerysets.txt +++ b/docs/ref/contrib/gis/geoquerysets.txt @@ -1026,7 +1026,7 @@ Keyword Argument Description representation -- the default value is 8. ===================== ===================================================== -__ http://code.google.com/apis/kml/documentation/ +__ https://developers.google.com/kml/documentation/ ``svg`` ~~~~~~~ @@ -1185,7 +1185,7 @@ Keyword Argument Description details. ===================== ===================================================== -__ http://download.oracle.com/docs/html/B14255_01/sdo_intro.htm#sthref150 +__ http://docs.oracle.com/html/B14255_01/sdo_intro.htm#sthref150 Aggregate Functions ------------------- @@ -1232,6 +1232,6 @@ Returns the same as the :meth:`GeoQuerySet.union` aggregate method. .. rubric:: Footnotes .. [#fnde9im] *See* `OpenGIS Simple Feature Specification For SQL <http://www.opengis.org/docs/99-049.pdf>`_, at Ch. 2.1.13.2, p. 2-13 (The Dimensionally Extended Nine-Intersection Model). -.. [#fnsdorelate] *See* `SDO_RELATE documentation <http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14255/sdo_operat.htm#sthref845>`_, from Ch. 11 of the Oracle Spatial User's Guide and Manual. +.. [#fnsdorelate] *See* `SDO_RELATE documentation <http://docs.oracle.com/cd/B19306_01/appdev.102/b14255/sdo_operat.htm#sthref845>`_, from Ch. 11 of the Oracle Spatial User's Guide and Manual. .. [#fncovers] For an explanation of this routine, read `Quirks of the "Contains" Spatial Predicate <http://lin-ear-th-inking.blogspot.com/2007/06/subtleties-of-ogc-covers-spatial.html>`_ by Martin Davis (a PostGIS developer). .. [#fncontainsproperly] Refer to the PostGIS ``ST_ContainsProperly`` `documentation <http://postgis.refractions.net/documentation/manual-1.4/ST_ContainsProperly.html>`_ for more details. diff --git a/docs/ref/contrib/gis/geos.txt b/docs/ref/contrib/gis/geos.txt index 1b32265e55..eda9617381 100644 --- a/docs/ref/contrib/gis/geos.txt +++ b/docs/ref/contrib/gis/geos.txt @@ -324,7 +324,7 @@ and Z values that are a part of this geometry. Returns the Well-Known Text of the geometry (an OGC standard). -__ http://code.google.com/apis/kml/documentation/ +__ https://developers.google.com/kml/documentation/ Spatial Predicate Methods ~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -891,7 +891,7 @@ Returns the WKT of the given geometry. Example:: .. rubric:: Footnotes -.. [#fnogc] *See* `PostGIS EWKB, EWKT and Canonical Forms <http://postgis.refractions.net/docs/ch04.html#id2591381>`_, PostGIS documentation at Ch. 4.1.2. +.. [#fnogc] *See* `PostGIS EWKB, EWKT and Canonical Forms <http://postgis.refractions.net/docs/using_postgis_dbmanagement.html#EWKB_EWKT>`_, PostGIS documentation at Ch. 4.1.2. .. [#fncascadedunion] For more information, read Paul Ramsey's blog post about `(Much) Faster Unions in PostGIS 1.4 <http://blog.cleverelephant.ca/2009/01/must-faster-unions-in-postgis-14.html>`_ and Martin Davis' blog post on `Fast polygon merging in JTS using Cascaded Union <http://lin-ear-th-inking.blogspot.com/2007/11/fast-polygon-merging-in-jts-using.html>`_. Settings diff --git a/docs/ref/contrib/gis/install.txt b/docs/ref/contrib/gis/install.txt index 4b7ee89a52..5ee6d5153d 100644 --- a/docs/ref/contrib/gis/install.txt +++ b/docs/ref/contrib/gis/install.txt @@ -81,7 +81,7 @@ Program Description Required ======================== ==================================== ================================ ========================== :ref:`GEOS <ref-geos>` Geometry Engine Open Source Yes 3.3, 3.2, 3.1, 3.0 `PROJ.4`_ Cartographic Projections library Yes (PostgreSQL and SQLite only) 4.7, 4.6, 4.5, 4.4 -:ref:`GDAL <ref-gdal>` Geospatial Data Abstraction Library No (but, required for SQLite) 1.8, 1.7, 1.6, 1.5, 1.4 +:ref:`GDAL <ref-gdal>` Geospatial Data Abstraction Library No (but, required for SQLite) 1.9, 1.8, 1.7, 1.6, 1.5 :ref:`GeoIP <ref-geoip>` IP-based geolocation library No 1.4 `PostGIS`__ Spatial extensions for PostgreSQL Yes (PostgreSQL only) 1.5, 1.4, 1.3 `SpatiaLite`__ Spatial extensions for SQLite Yes (SQLite only) 3.0, 2.4, 2.3 @@ -102,7 +102,7 @@ Program Description Required .. _PROJ.4: http://trac.osgeo.org/proj/ __ http://postgis.refractions.net/ -__ http://www.gaia-gis.it/spatialite/index.html +__ http://www.gaia-gis.it/gaia-sins/ .. _build_from_source: @@ -233,7 +233,7 @@ installed prior to building PostGIS. The `psycopg2`_ module is required for use as the database adaptor when using GeoDjango with PostGIS. -.. _psycopg2: http://initd.org/projects/psycopg2 +.. _psycopg2: http://initd.org/psycopg/ First download the source archive, and extract:: @@ -270,9 +270,9 @@ supports :ref:`GDAL's vector data <ref-gdal>` capabilities [#]_. First download the latest GDAL release version and untar the archive:: - $ wget http://download.osgeo.org/gdal/gdal-1.8.1.tar.gz - $ tar xzf gdal-1.8.1.tar.gz - $ cd gdal-1.8.1 + $ wget http://download.osgeo.org/gdal/gdal-1.9.1.tar.gz + $ tar xzf gdal-1.9.1.tar.gz + $ cd gdal-1.9.1 Configure, make and install:: @@ -376,7 +376,7 @@ SpatiaLite. After installation is complete, don't forget to read the post-installation docs on :ref:`create_spatialite_db`. -__ http://www.gaia-gis.it/spatialite/index.html +__ http://www.gaia-gis.it/gaia-sins/ .. _sqlite: @@ -457,7 +457,7 @@ Finally, do the same for the SpatiaLite tools:: $ ./configure --target=macosx -__ http://www.gaia-gis.it/spatialite/sources.html +__ http://www.gaia-gis.it/gaia-sins/libspatialite-sources/ .. _pysqlite2: @@ -664,7 +664,7 @@ community! You can: and specify the component as "GIS". __ http://groups.google.com/group/geodjango -__ https://code.djangoproject.com/simpleticket +__ https://code.djangoproject.com/newticket .. _libsettings: @@ -762,13 +762,13 @@ Python ^^^^^^ Although OS X comes with Python installed, users can use framework -installers (`2.5`__ and `2.6`__ are available) provided by +installers (`2.6`__ and `2.7`__ are available) provided by the Python Software Foundation. An advantage to using the installer is that OS X's Python will remain "pristine" for internal operating system use. -__ http://python.org/ftp/python/2.5.4/python-2.5.4-macosx.dmg -__ http://python.org/ftp/python/2.6.2/python-2.6.2-macosx2009-04-16.dmg +__ http://python.org/ftp/python/2.6.6/python-2.6.6-macosx10.3.dmg +__ http://python.org/ftp/python/2.7.3/ .. note:: @@ -838,17 +838,6 @@ your ``.profile`` to be able to run the package programs from the command-line:: __ http://www.kyngchaos.com/software/frameworks __ http://www.kyngchaos.com/software/postgres -.. note:: - - Use of these binaries requires Django 1.0.3 and above. If you are - using a previous version of Django (like 1.0.2), then you will have - to add the following in your settings: - - .. code-block:: python - - GEOS_LIBRARY_PATH='/Library/Frameworks/GEOS.framework/GEOS' - GDAL_LIBRARY_PATH='/Library/Frameworks/GDAL.framework/GDAL' - .. _psycopg2_kyngchaos: psycopg2 @@ -903,7 +892,7 @@ add the following to your ``settings.py``: SPATIALITE_LIBRARY_PATH='/Library/Frameworks/SQLite3.framework/SQLite3' -__ http://www.gaia-gis.it/spatialite/binaries.html +__ http://www.gaia-gis.it/spatialite-2.3.1/binaries.html .. _fink: @@ -1045,61 +1034,11 @@ Optional packages to consider: do not plan on doing any database transformation of geometries to the Google projection (900913). -.. _heron: - -8.04 and lower -~~~~~~~~~~~~~~ - -The 8.04 (and lower) versions of Ubuntu use GEOS v2.2.3 in their binary packages, -which is incompatible with GeoDjango. Thus, do *not* use the binary packages -for GEOS or PostGIS and build some prerequisites from source, per the instructions -in this document; however, it is okay to use the PostgreSQL binary packages. - -For more details, please see the Debian instructions for :ref:`etch` below. - .. _debian: Debian ------ -.. _etch: - -4.0 (Etch) -^^^^^^^^^^ - -The situation here is the same as that of Ubuntu :ref:`heron` -- in other words, -some packages must be built from source to work properly with GeoDjango. - -Binary packages -~~~~~~~~~~~~~~~ -The following command will install acceptable binary packages, as well as -the development tools necessary to build the rest of the requirements: - -.. code-block:: bash - - $ sudo apt-get install binutils bzip2 gcc g++ flex make postgresql-8.1 \ - postgresql-server-dev-8.1 python-ctypes python-psycopg2 python-setuptools - -Required package information: - -* ``binutils``: for ctypes to find libraries -* ``bzip2``: for decompressing the source packages -* ``gcc``, ``g++``, ``make``: GNU developer tools used to compile the libraries -* ``flex``: required to build PostGIS -* ``postgresql-8.1`` -* ``postgresql-server-dev-8.1``: for ``pg_config`` -* ``python-psycopg2`` - -Optional packages: - -* ``libgeoip``: for :ref:`GeoIP <ref-geoip>` support - -Source packages -~~~~~~~~~~~~~~~ -You will still have to install :ref:`geosbuild`, :ref:`proj4`, -:ref:`postgis`, and :ref:`gdalbuild` from source. Please follow the -directions carefully. - .. _lenny: 5.0 (Lenny) @@ -1314,8 +1253,8 @@ may be executed from the SQL Shell as the ``postgres`` user:: .. rubric:: Footnotes .. [#] The datum shifting files are needed for converting data to and from certain projections. - For example, the PROJ.4 string for the `Google projection (900913) - <http://spatialreference.org/ref/epsg/900913/proj4>`_ requires the + For example, the PROJ.4 string for the `Google projection (900913 or 3857) + <http://spatialreference.org/ref/sr-org/6864/prj/>`_ requires the ``null`` grid file only included in the extra datum shifting files. It is easier to install the shifting files now, then to have debug a problem caused by their absence later. diff --git a/docs/ref/contrib/gis/model-api.txt b/docs/ref/contrib/gis/model-api.txt index 462df50d64..8c5274e6d3 100644 --- a/docs/ref/contrib/gis/model-api.txt +++ b/docs/ref/contrib/gis/model-api.txt @@ -142,7 +142,7 @@ __ http://en.wikipedia.org/wiki/Geodesy __ http://en.wikipedia.org/wiki/Great_circle __ http://www.spatialreference.org/ref/epsg/2796/ __ http://spatialreference.org/ -__ http://welcome.warnercnr.colostate.edu/class_info/nr502/lg3/datums_coordinates/spcs.html +__ http://web.archive.org/web/20080302095452/http://welcome.warnercnr.colostate.edu/class_info/nr502/lg3/datums_coordinates/spcs.html ``spatial_index`` ----------------- @@ -252,7 +252,7 @@ for example:: qs = Address.objects.filter(zipcode__poly__contains='POINT(-104.590948 38.319914)') .. rubric:: Footnotes -.. [#fnogc] OpenGIS Consortium, Inc., `Simple Feature Specification For SQL <http://www.opengis.org/docs/99-049.pdf>`_, Document 99-049 (May 5, 1999). +.. [#fnogc] OpenGIS Consortium, Inc., `Simple Feature Specification For SQL <http://www.opengeospatial.org/standards/sfs>`_. .. [#fnogcsrid] *See id.* at Ch. 2.3.8, p. 39 (Geometry Values and Spatial Reference Systems). .. [#fnsrid] Typically, SRID integer corresponds to an EPSG (`European Petroleum Survey Group <http://www.epsg.org>`_) identifier. However, it may also be associated with custom projections defined in spatial database's spatial reference systems table. .. [#fnharvard] Harvard Graduate School of Design, `An Overview of Geodesy and Geographic Referencing Systems <http://www.gsd.harvard.edu/gis/manual/projections/fundamentals/>`_. This is an excellent resource for an overview of principles relating to geographic and Cartesian coordinate systems. diff --git a/docs/ref/contrib/gis/sitemaps.txt b/docs/ref/contrib/gis/sitemaps.txt index 75bddd3b86..0ab8f75825 100644 --- a/docs/ref/contrib/gis/sitemaps.txt +++ b/docs/ref/contrib/gis/sitemaps.txt @@ -2,10 +2,10 @@ Geographic Sitemaps =================== -Google's sitemap protocol has been recently extended to support geospatial -content. [#]_ This includes the addition of the ``<url>`` child element +Google's sitemap protocol used to include geospatial content support. [#]_ +This included the addition of the ``<url>`` child element ``<geo:geo>``, which tells Google that the content located at the URL is -geographic in nature. [#]_ +geographic in nature. This is now obsolete. Example ======= @@ -23,5 +23,4 @@ Reference ----------------- .. rubric:: Footnotes -.. [#] Google, Inc., `What is a Geo Sitemap? <http://www.google.com/support/webmasters/bin/answer.py?answer=94554>`_. -.. [#] Google, Inc., `Submit Your Geo Content to Google <http://code.google.com/apis/kml/documentation/kmlSearch.html>`_. +.. [#] Google, Inc., `What is a Geo Sitemap? <http://support.google.com/webmasters/bin/answer.py?answer=94555>`_. diff --git a/docs/ref/contrib/gis/tutorial.txt b/docs/ref/contrib/gis/tutorial.txt index 395eac1821..3a63493137 100644 --- a/docs/ref/contrib/gis/tutorial.txt +++ b/docs/ref/contrib/gis/tutorial.txt @@ -784,4 +784,4 @@ option class in your ``admin.py`` file:: .. [#] Special thanks to Bjørn Sandvik of `thematicmapping.org <http://thematicmapping.org>`_ for providing and maintaining this data set. .. [#] GeoDjango basic apps was written by Dane Springmeyer, Josh Livni, and Christopher Schmidt. .. [#] Here the point is for the `University of Houston Law Center <http://www.law.uh.edu/>`_. -.. [#] Open Geospatial Consortium, Inc., `OpenGIS Simple Feature Specification For SQL <http://www.opengis.org/docs/99-049.pdf>`_, Document 99-049. +.. [#] Open Geospatial Consortium, Inc., `OpenGIS Simple Feature Specification For SQL <http://www.opengeospatial.org/standards/sfs>`_. diff --git a/docs/ref/contrib/localflavor.txt b/docs/ref/contrib/localflavor.txt index 61c8c7ae47..4595f51d9e 100644 --- a/docs/ref/contrib/localflavor.txt +++ b/docs/ref/contrib/localflavor.txt @@ -93,7 +93,7 @@ Here's an example of how to use them:: class MyForm(forms.Form): my_date_field = generic.forms.DateField() -.. _ISO 3166 country codes: http://www.iso.org/iso/country_codes/iso_3166_code_lists/english_country_names_and_code_elements.htm +.. _ISO 3166 country codes: http://www.iso.org/iso/country_codes.htm .. _Argentina: `Argentina (ar)`_ .. _Australia: `Australia (au)`_ .. _Austria: `Austria (at)`_ @@ -158,7 +158,7 @@ any code you'd like to contribute. One thing we ask is that you please use Unicode objects (``u'mystring'``) for strings, rather than setting the encoding in the file. See any of the existing flavors for examples. -.. _create a ticket: https://code.djangoproject.com/simpleticket +.. _create a ticket: https://code.djangoproject.com/newticket Localflavor and backwards compatibility ======================================= @@ -713,7 +713,7 @@ Italy (``it``) A form field that validates input as an Italian social security number (`codice fiscale`_). -.. _codice fiscale: http://www.agenziaentrate.it/ilwwcm/connect/Nsi/Servizi/Codice+fiscale+-+tessera+sanitaria/NSI+Informazioni+sulla+codificazione+delle+persone+fisiche +.. _codice fiscale: http://www.agenziaentrate.gov.it/wps/content/Nsilib/Nsi/Home/CosaDeviFare/Richiedere/Codice+fiscale+e+tessera+sanitaria/Richiesta+TS_CF/SchedaI/Informazioni+codificazione+pf/ .. class:: it.forms.ITVatNumberField diff --git a/docs/ref/contrib/messages.txt b/docs/ref/contrib/messages.txt index da6336e832..6929a3b0d0 100644 --- a/docs/ref/contrib/messages.txt +++ b/docs/ref/contrib/messages.txt @@ -54,7 +54,8 @@ Storage backends ---------------- The messages framework can use different backends to store temporary messages. -To change which backend is being used, add a `MESSAGE_STORAGE`_ to your +If the default FallbackStorage isn't suitable to your needs, you can change +which backend is being used by adding a `MESSAGE_STORAGE`_ to your settings, referencing the module and class of the storage class. For example:: @@ -62,7 +63,7 @@ example:: The value should be the full path of the desired storage class. -Four storage classes are included: +Three storage classes are available: ``'django.contrib.messages.storage.session.SessionStorage'`` This class stores all messages inside of the request's session. It @@ -74,6 +75,8 @@ Four storage classes are included: messages are dropped if the cookie data size would exceed 4096 bytes. ``'django.contrib.messages.storage.fallback.FallbackStorage'`` + This is the default storage class. + This class first uses CookieStorage for all messages, falling back to using SessionStorage for the messages that could not fit in a single cookie. diff --git a/docs/ref/contrib/sitemaps.txt b/docs/ref/contrib/sitemaps.txt index d775092eae..2393a4a9a3 100644 --- a/docs/ref/contrib/sitemaps.txt +++ b/docs/ref/contrib/sitemaps.txt @@ -410,7 +410,7 @@ generate a Google News compatible sitemap: {% endspaceless %} </urlset> -.. _`Google news sitemaps`: http://www.google.com/support/webmasters/bin/answer.py?hl=en&answer=74288 +.. _`Google news sitemaps`: http://support.google.com/webmasters/bin/answer.py?hl=en&answer=74288 Pinging Google ============== diff --git a/docs/ref/contrib/staticfiles.txt b/docs/ref/contrib/staticfiles.txt index 126bcdd4e6..cbe8ad54b8 100644 --- a/docs/ref/contrib/staticfiles.txt +++ b/docs/ref/contrib/staticfiles.txt @@ -387,6 +387,17 @@ The previous example is equal to calling the ``url`` method of an instance of useful when using a non-local storage backend to deploy files as documented in :ref:`staticfiles-from-cdn`. +.. versionadded:: 1.5 + +If you'd like to retrieve a static URL without displaying it, you can use a +slightly different call: + +.. code-block:: html+django + + {% load static from staticfiles %} + {% static "images/hi.jpg" as myphoto %} + <img src="{{ myphoto }}" alt="Hi!" /> + Other Helpers ============= diff --git a/docs/ref/databases.txt b/docs/ref/databases.txt index 600de8ed3a..74e6b48f07 100644 --- a/docs/ref/databases.txt +++ b/docs/ref/databases.txt @@ -31,7 +31,7 @@ attempt to use the ``StdDev(sample=False)`` or ``Variance(sample=False)`` aggregate with a database backend that falls within the affected release range. .. _known to be faulty: http://archives.postgresql.org/pgsql-bugs/2007-07/msg00046.php -.. _Release 8.2.5: http://developer.postgresql.org/pgdocs/postgres/release-8-2-5.html +.. _Release 8.2.5: http://www.postgresql.org/docs/devel/static/release-8-2-5.html Optimizing PostgreSQL's configuration ------------------------------------- @@ -111,7 +111,7 @@ outputs a single ``CREATE INDEX`` statement. However, if the database type for the field is either ``varchar`` or ``text`` (e.g., used by ``CharField``, ``FileField``, and ``TextField``), then Django will create an additional index that uses an appropriate `PostgreSQL operator class`_ -for the column. The extra index is necessary to correctly perfrom +for the column. The extra index is necessary to correctly perform lookups that use the ``LIKE`` operator in their SQL, as is done with the ``contains`` and ``startswith`` lookup types. @@ -335,7 +335,9 @@ storage engine, you have a couple of options. } This sets the default storage engine upon connecting to the database. - After your tables have been created, you should remove this option. + After your tables have been created, you should remove this option as it + adds a query that is only needed during table creation to each database + connection. * Another method for changing the storage engine is described in AlterModelOnSyncDB_. diff --git a/docs/ref/django-admin.txt b/docs/ref/django-admin.txt index 360c0ae4d3..c4295c68d5 100644 --- a/docs/ref/django-admin.txt +++ b/docs/ref/django-admin.txt @@ -224,8 +224,8 @@ flush .. django-admin:: flush -Returns the database to the state it was in immediately after syncdb was -executed. This means that all data will be removed from the database, any +Returns the database to the state it was in immediately after :djadmin:`syncdb` +was executed. This means that all data will be removed from the database, any post-synchronization handlers will be re-executed, and the ``initial_data`` fixture will be re-installed. @@ -668,6 +668,7 @@ Example usage:: .. versionadded:: 1.4 +Since version 1.4, the development server is multithreaded by default. Use the ``--nothreading`` option to disable the use of threading in the development server. @@ -742,6 +743,24 @@ use the ``--plain`` option, like so:: django-admin.py shell --plain +.. versionchanged:: 1.5 + +If you would like to specify either IPython or bpython as your interpreter if +you have both installed you can specify an alternative interpreter interface +with the ``-i`` or ``--interface`` options like so:: + +IPython:: + + django-admin.py shell -i ipython + django-admin.py shell --interface ipython + + +bpython:: + + django-admin.py shell -i bpython + django-admin.py shell --interface bpython + + .. _IPython: http://ipython.scipy.org/ .. _bpython: http://bpython-interpreter.org/ @@ -887,7 +906,8 @@ through the template engine: the files whose extensions match the with the ``--name`` option. The :class:`template context <django.template.Context>` used is: -- Any option passed to the startapp command +- Any option passed to the startapp command (among the command's supported + options) - ``app_name`` -- the app name as passed to the command - ``app_directory`` -- the full path of the newly created app diff --git a/docs/ref/forms/fields.txt b/docs/ref/forms/fields.txt index 486d49d796..082ec17a35 100644 --- a/docs/ref/forms/fields.txt +++ b/docs/ref/forms/fields.txt @@ -591,7 +591,11 @@ For each field, we describe the default widget used if you don't specify * Error message keys: ``required``, ``invalid``, ``missing``, ``empty``, ``invalid_image`` - Using an ImageField requires that the `Python Imaging Library`_ is installed. + Using an ``ImageField`` requires that the `Python Imaging Library`_ (PIL) + is installed and supports the image formats you use. If you encounter a + ``corrupt image`` error when you upload an image, it usually means PIL + doesn't understand its format. To fix this, install the appropriate + library and reinstall PIL. When you use an ``ImageField`` on a form, you must also remember to :ref:`bind the file data to the form <binding-uploaded-files>`. diff --git a/docs/ref/forms/widgets.txt b/docs/ref/forms/widgets.txt index 88d0d706cd..fb7657349a 100644 --- a/docs/ref/forms/widgets.txt +++ b/docs/ref/forms/widgets.txt @@ -75,7 +75,7 @@ changing :attr:`ChoiceField.choices` will update :attr:`Select.choices`. For example:: >>> from django import forms - >>> CHOICES = (('1', 'First',), ('2', 'Second',))) + >>> CHOICES = (('1', 'First',), ('2', 'Second',)) >>> choice_field = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES) >>> choice_field.choices [('1', 'First'), ('2', 'Second')] diff --git a/docs/ref/models/fields.txt b/docs/ref/models/fields.txt index 23dcf4bd9f..5039ba4373 100644 --- a/docs/ref/models/fields.txt +++ b/docs/ref/models/fields.txt @@ -1074,15 +1074,14 @@ the model is related. This works exactly the same as it does for Database Representation ~~~~~~~~~~~~~~~~~~~~~~~ -Behind the scenes, Django creates an intermediary join table to -represent the many-to-many relationship. By default, this table name -is generated using the name of the many-to-many field and the model -that contains it. Since some databases don't support table names above -a certain length, these table names will be automatically truncated to -64 characters and a uniqueness hash will be used. This means you might -see table names like ``author_books_9cdf4``; this is perfectly normal. -You can manually provide the name of the join table using the -:attr:`~ManyToManyField.db_table` option. +Behind the scenes, Django creates an intermediary join table to represent the +many-to-many relationship. By default, this table name is generated using the +name of the many-to-many field and the name of the table for the model that +contains it. Since some databases don't support table names above a certain +length, these table names will be automatically truncated to 64 characters and a +uniqueness hash will be used. This means you might see table names like +``author_books_9cdf4``; this is perfectly normal. You can manually provide the +name of the join table using the :attr:`~ManyToManyField.db_table` option. .. _manytomany-arguments: @@ -1138,8 +1137,9 @@ that control how the relationship functions. .. attribute:: ManyToManyField.db_table The name of the table to create for storing the many-to-many data. If this - is not provided, Django will assume a default name based upon the names of - the two tables being joined. + is not provided, Django will assume a default name based upon the names of: + the table for the model defining the relationship and the name of the field + itself. .. _ref-onetoone: diff --git a/docs/ref/models/instances.txt b/docs/ref/models/instances.txt index 3ae994bc5b..509ea9d30e 100644 --- a/docs/ref/models/instances.txt +++ b/docs/ref/models/instances.txt @@ -25,6 +25,41 @@ The keyword arguments are simply the names of the fields you've defined on your model. Note that instantiating a model in no way touches your database; for that, you need to :meth:`~Model.save()`. +.. note:: + + You may be tempted to customize the model by overriding the ``__init__`` + method. If you do so, however, take care not to change the calling + signature as any change may prevent the model instance from being saved. + Rather than overriding ``__init__``, try using one of these approaches: + + 1. Add a classmethod on the model class:: + + class Book(models.Model): + title = models.CharField(max_length=100) + + @classmethod + def create(cls, title): + book = cls(title=title) + # do something with the book + return book + + book = Book.create("Pride and Prejudice") + + 2. Add a method on a custom manager (usually preferred):: + + class BookManager(models.Manager): + def create_book(title): + book = self.create(title=title) + # do something with the book + return book + + class Book(models.Model): + title = models.CharField(max_length=100) + + objects = BookManager() + + book = Book.objects.create_book("Pride and Prejudice") + .. _validating-objects: Validating objects @@ -604,4 +639,3 @@ described in :ref:`Field lookups <field-lookups>`. Note that in the case of identical date values, these methods will use the primary key as a tie-breaker. This guarantees that no records are skipped or duplicated. That also means you cannot use those methods on unsaved objects. - diff --git a/docs/ref/models/options.txt b/docs/ref/models/options.txt index 6ca3d3b2d0..9d076f6274 100644 --- a/docs/ref/models/options.txt +++ b/docs/ref/models/options.txt @@ -244,12 +244,12 @@ Django quotes column and table names behind the scenes. unique_together = (("driver", "restaurant"),) - This is a list of lists of fields that must be unique when considered together. + This is a tuple of tuples that must be unique when considered together. It's used in the Django admin and is enforced at the database level (i.e., the appropriate ``UNIQUE`` statements are included in the ``CREATE TABLE`` statement). - For convenience, unique_together can be a single list when dealing with a single + For convenience, unique_together can be a single tuple when dealing with a single set of fields:: unique_together = ("driver", "restaurant") diff --git a/docs/ref/models/querysets.txt b/docs/ref/models/querysets.txt index eef22728ab..8c188c67c3 100644 --- a/docs/ref/models/querysets.txt +++ b/docs/ref/models/querysets.txt @@ -1081,11 +1081,13 @@ to ``defer()``:: # Load all fields immediately. my_queryset.defer(None) +.. versionchanged:: 1.5 + Some fields in a model won't be deferred, even if you ask for them. You can never defer the loading of the primary key. If you are using :meth:`select_related()` to retrieve related models, you shouldn't defer the -loading of the field that connects from the primary model to the related one -(at the moment, that doesn't raise an error, but it will eventually). +loading of the field that connects from the primary model to the related +one, doing so will result in an error. .. note:: @@ -1145,9 +1147,12 @@ logically:: # existing set of fields). Entry.objects.defer("body").only("headline", "body") +.. versionchanged:: 1.5 + All of the cautions in the note for the :meth:`defer` documentation apply to ``only()`` as well. Use it cautiously and only after exhausting your other -options. +options. Also note that using :meth:`only` and omitting a field requested +using :meth:`select_related` is an error as well. using ~~~~~ @@ -1345,7 +1350,7 @@ has a side effect on your data. For more, see `Safe methods`_ in the HTTP spec. bulk_create ~~~~~~~~~~~ -.. method:: bulk_create(objs) +.. method:: bulk_create(objs, batch_size=None) .. versionadded:: 1.4 @@ -1367,20 +1372,12 @@ This has a number of caveats though: * If the model's primary key is an :class:`~django.db.models.AutoField` it does not retrieve and set the primary key attribute, as ``save()`` does. -.. admonition:: Limits of SQLite - - SQLite sets a limit on the number of parameters per SQL statement. The - maximum is defined by the SQLITE_MAX_VARIABLE_NUMBER_ compilation option, - which defaults to 999. For instance, if your model has 8 fields (including - the primary key), you cannot create more than 999 // 8 = 124 instances at - a time. If you exceed this limit, you'll get an exception:: +The ``batch_size`` parameter controls how many objects are created in single +query. The default is to create all objects in one batch, except for SQLite +where the default is such that at maximum 999 variables per query is used. - django.db.utils.DatabaseError: too many SQL variables - - If your application's performance requirements exceed SQLite's limits, you - should switch to another database engine, such as PostgreSQL. - -.. _SQLITE_MAX_VARIABLE_NUMBER: http://sqlite.org/limits.html#max_variable_number +.. versionadded:: 1.5 + The ``batch_size`` parameter was added in version 1.5. count ~~~~~ @@ -1763,22 +1760,6 @@ This queryset will be evaluated as subselect statement:: SELECT ... WHERE blog.id IN (SELECT id FROM ... WHERE NAME LIKE '%Cheddar%') -The above code fragment could also be written as follows:: - - inner_q = Blog.objects.filter(name__contains='Cheddar').values('pk').query - entries = Entry.objects.filter(blog__in=inner_q) - -.. warning:: - - This ``query`` attribute should be considered an opaque internal attribute. - It's fine to use it like above, but its API may change between Django - versions. - -This second form is a bit less readable and unnatural to write, since it -accesses the internal ``query`` attribute and requires a ``ValuesQuerySet``. -If your code doesn't require compatibility with Django 1.0, use the first -form, passing in a queryset directly. - If you pass in a ``ValuesQuerySet`` or ``ValuesListQuerySet`` (the result of calling ``values()`` or ``values_list()`` on a queryset) as the value to an ``__in`` lookup, you need to ensure you are only extracting one field in the diff --git a/docs/ref/request-response.txt b/docs/ref/request-response.txt index d2b6f35b84..551ee00c6b 100644 --- a/docs/ref/request-response.txt +++ b/docs/ref/request-response.txt @@ -606,11 +606,10 @@ Attributes Methods ------- -.. method:: HttpResponse.__init__(content='', mimetype=None, status=200, content_type=DEFAULT_CONTENT_TYPE) +.. method:: HttpResponse.__init__(content='', content_type=None, status=200) - Instantiates an ``HttpResponse`` object with the given page content (a - string) and MIME type. The :setting:`DEFAULT_CONTENT_TYPE` is - ``'text/html'``. + Instantiates an ``HttpResponse`` object with the given page content and + content type. ``content`` should be an iterator or a string. If it's an iterator, it should return strings, and those strings will be @@ -618,15 +617,15 @@ Methods an iterator or a string, it will be converted to a string when accessed. + ``content_type`` is the MIME type optionally completed by a character set + encoding and is used to fill the HTTP ``Content-Type`` header. If not + specified, it is formed by the :setting:`DEFAULT_CONTENT_TYPE` and + :setting:`DEFAULT_CHARSET` settings, by default: "`text/html; charset=utf-8`". + + Historically, this parameter was called ``mimetype`` (now deprecated). + ``status`` is the `HTTP Status code`_ for the response. - ``content_type`` is an alias for ``mimetype``. Historically, this parameter - was only called ``mimetype``, but since this is actually the value included - in the HTTP ``Content-Type`` header, it can also include the character set - encoding, which makes it more than just a MIME type specification. - If ``mimetype`` is specified (not ``None``), that value is used. - Otherwise, ``content_type`` is used. If neither is given, the - :setting:`DEFAULT_CONTENT_TYPE` setting is used. .. method:: HttpResponse.__setitem__(header, value) @@ -684,7 +683,7 @@ Methods risk of client side script accessing the protected cookie data. - .. _HTTPOnly: http://www.owasp.org/index.php/HTTPOnly + .. _HTTPOnly: https://www.owasp.org/index.php/HTTPOnly .. method:: HttpResponse.set_signed_cookie(key, value='', salt='', max_age=None, expires=None, path='/', domain=None, secure=None, httponly=True) diff --git a/docs/ref/settings.txt b/docs/ref/settings.txt index 627aa5007f..72d60453c3 100644 --- a/docs/ref/settings.txt +++ b/docs/ref/settings.txt @@ -1675,7 +1675,7 @@ consistently by all browsers. However, when it is honored, it can be a useful way to mitigate the risk of client side script accessing the protected cookie data. -.. _HTTPOnly: http://www.owasp.org/index.php/HTTPOnly +.. _HTTPOnly: https://www.owasp.org/index.php/HTTPOnly .. versionchanged:: 1.4 The default value of the setting was changed from ``False`` to ``True``. diff --git a/docs/ref/templates/api.txt b/docs/ref/templates/api.txt index 6142dd7017..bd2b4c6e9d 100644 --- a/docs/ref/templates/api.txt +++ b/docs/ref/templates/api.txt @@ -370,6 +370,7 @@ and return a dictionary of items to be merged into the context. By default, "django.core.context_processors.i18n", "django.core.context_processors.media", "django.core.context_processors.static", + "django.core.context_processors.tz", "django.contrib.messages.context_processors.messages") In addition to these, ``RequestContext`` always uses @@ -648,14 +649,24 @@ class. Here are the template loaders that come with Django: INSTALLED_APPS = ('myproject.polls', 'myproject.music') - ...then ``get_template('foo.html')`` will look for templates in these + ...then ``get_template('foo.html')`` will look for ``foo.html`` in these directories, in this order: - * ``/path/to/myproject/polls/templates/foo.html`` - * ``/path/to/myproject/music/templates/foo.html`` + * ``/path/to/myproject/polls/templates/`` + * ``/path/to/myproject/music/templates/`` - Note that the loader performs an optimization when it is first imported: It - caches a list of which :setting:`INSTALLED_APPS` packages have a + ... and will use the one it finds first. + + The order of :setting:`INSTALLED_APPS` is significant! For example, if you + want to customize the Django admin, you might choose to override the + standard ``admin/base_site.html`` template, from ``django.contrib.admin``, + with your own ``admin/base_site.html`` in ``myproject.polls``. You must + then make sure that your ``myproject.polls`` comes *before* + ``django.contrib.admin`` in :setting:`INSTALLED_APPS`, otherwise + ``django.contrib.admin``'s will be loaded first and yours will be ignored. + + Note that the loader performs an optimization when it is first imported: + it caches a list of which :setting:`INSTALLED_APPS` packages have a ``templates`` subdirectory. This loader is enabled by default. @@ -773,7 +784,7 @@ Using an alternative template language The Django ``Template`` and ``Loader`` classes implement a simple API for loading and rendering templates. By providing some simple wrapper classes that implement this API we can use third party template systems like `Jinja2 -<http://jinja.pocoo.org/2/>`_ or `Cheetah <http://www.cheetahtemplate.org/>`_. This +<http://jinja.pocoo.org/docs/>`_ or `Cheetah <http://www.cheetahtemplate.org/>`_. This allows us to use third-party template libraries without giving up useful Django features like the Django ``Context`` object and handy shortcuts like :func:`~django.shortcuts.render_to_response()`. diff --git a/docs/ref/templates/builtins.txt b/docs/ref/templates/builtins.txt index 6f341e9f97..500a47c6f1 100644 --- a/docs/ref/templates/builtins.txt +++ b/docs/ref/templates/builtins.txt @@ -419,7 +419,7 @@ will be interpreted like: if (athlete_list and coach_list) or cheerleader_list -Use of actual brackets in the :ttag:`if` tag is invalid syntax. If you need +Use of actual parentheses in the :ttag:`if` tag is invalid syntax. If you need them to indicate precedence, you should use nested :ttag:`if` tags. :ttag:`if` tags may also use the operators ``==``, ``!=``, ``<``, ``>``, @@ -1047,12 +1047,12 @@ Django's syntax. For example:: {{if dying}}Still alive.{{/if}} {% endverbatim %} -You can also specify an alternate closing tag:: +You can also designate a specific closing tag, allowing the use of +``{% endverbatim %}`` as part of the unrendered contents:: - {% verbatim finished %} - The verbatim tag looks like this: - {% verbatim %}{% endverbatim %} - {% finished %} + {% verbatim myblock %} + Avoid template rendering via the {% verbatim %}{% endverbatim %} block. + {% endverbatim myblock %} .. templatetag:: widthratio @@ -2354,6 +2354,17 @@ It is also able to consume standard context variables, e.g. assuming a {% load static %} <link rel="stylesheet" href="{% static user_stylesheet %}" type="text/css" media="screen" /> +If you'd like to retrieve a static URL without displaying it, you can use a +slightly different call:: + +.. versionadded:: 1.5 + +.. code-block:: html+django + + {% load static %} + {% static "images/hi.jpg" as myphoto %} + <img src="{{ myphoto }}"></img> + .. note:: The :mod:`staticfiles<django.contrib.staticfiles>` contrib app also ships diff --git a/docs/ref/utils.txt b/docs/ref/utils.txt index b323f0629f..c2f2025bc3 100644 --- a/docs/ref/utils.txt +++ b/docs/ref/utils.txt @@ -112,10 +112,14 @@ to distinguish caches by the ``Accept-language`` header. .. method:: insert(index, key, value) + .. deprecated:: 1.5 + Inserts the key, value pair before the item with the given index. .. method:: value_for_index(index) + .. deprecated:: 1.5 + Returns the value of the item at the given zero-based index. Creating a new SortedDict @@ -246,13 +250,13 @@ For simplifying the selection of a generator use ``feedgenerator.DefaultFeed`` which is currently ``Rss201rev2Feed`` For definitions of the different versions of RSS, see: -http://diveintomark.org/archives/2004/02/04/incompatible-rss +http://web.archive.org/web/20110718035220/http://diveintomark.org/archives/2004/02/04/incompatible-rss .. function:: get_tag_uri(url, date) Creates a TagURI. - See http://diveintomark.org/archives/2004/05/28/howto-atom-id + See http://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id SyndicationFeed --------------- @@ -330,7 +334,7 @@ Rss201rev2Feed .. class:: Rss201rev2Feed(RssFeed) - Spec: http://blogs.law.harvard.edu/tech/rss + Spec: http://cyber.law.harvard.edu/rss/rss.html RssUserland091Feed ------------------ @@ -387,6 +391,67 @@ Atom1Feed input is a proper string, then add support for lazy translation objects at the end. +``django.utils.html`` +===================== + +.. module:: django.utils.html + :synopsis: HTML helper functions + +Usually you should build up HTML using Django's templates to make use of its +autoescape mechanism, using the utilities in :mod:`django.utils.safestring` +where appropriate. This module provides some additional low level utilitiesfor +escaping HTML. + +.. function:: escape(text) + + Returns the given text with ampersands, quotes and angle brackets encoded + for use in HTML. The input is first passed through + :func:`~django.utils.encoding.force_unicode` and the output has + :func:`~django.utils.safestring.mark_safe` applied. + +.. function:: conditional_escape(text) + + Similar to ``escape()``, except that it doesn't operate on pre-escaped strings, + so it will not double escape. + +.. function:: format_html(format_string, *args, **kwargs) + + This is similar to `str.format`_, except that it is appropriate for + building up HTML fragments. All args and kwargs are passed through + :func:`conditional_escape` before being passed to ``str.format``. + + For the case of building up small HTML fragments, this function is to be + preferred over string interpolation using ``%`` or ``str.format`` directly, + because it applies escaping to all arguments - just like the Template system + applies escaping by default. + + So, instead of writing: + + .. code-block:: python + + mark_safe(u"%s <b>%s</b> %s" % (some_html, + escape(some_text), + escape(some_other_text), + )) + + you should instead use: + + .. code-block:: python + + format_html(u"%{0} <b>{1}</b> {2}", + mark_safe(some_html), some_text, some_other_text) + + This has the advantage that you don't need to apply :func:`escape` to each + argument and risk a bug and an XSS vulnerability if you forget one. + + Note that although this function uses ``str.format`` to do the + interpolation, some of the formatting options provided by `str.format`_ + (e.g. number formatting) will not work, since all arguments are passed + through :func:`conditional_escape` which (ultimately) calls + :func:`~django.utils.encoding.force_unicode` on the values. + + +.. _str.format: http://docs.python.org/library/stdtypes.html#str.format ``django.utils.http`` ===================== diff --git a/docs/releases/1.0-beta-2.txt b/docs/releases/1.0-beta-2.txt index 2a2554432e..288ac8fbc1 100644 --- a/docs/releases/1.0-beta-2.txt +++ b/docs/releases/1.0-beta-2.txt @@ -46,7 +46,7 @@ Refactored documentation documentation files bundled with Django. .. _Sphinx: http://sphinx.pocoo.org/ -.. _online: http://docs.djangoproject.com/en/dev/ +.. _online: https://docs.djangoproject.com/ Along with these new features, the Django team has also been hard at work polishing Django's codebase for the final 1.0 release; this beta diff --git a/docs/releases/1.0.1.txt b/docs/releases/1.0.1.txt index 7901b8e219..d6d21afc01 100644 --- a/docs/releases/1.0.1.txt +++ b/docs/releases/1.0.1.txt @@ -18,7 +18,7 @@ Fixes and improvements in Django 1.0.1 Django 1.0.1 contains over two hundred fixes to the original Django 1.0 codebase; full details of every fix are available in `the -Subversion log of the 1.0.X branch`_, but here are some of the +history of the 1.0.X branch`_, but here are some of the highlights: * Several fixes in ``django.contrib.comments``, pertaining to RSS @@ -61,4 +61,4 @@ highlights: documentation, including both corrections to existing documents and expanded and new documentation. -.. _the Subversion log of the 1.0.X branch: https://code.djangoproject.com/log/django/branches/releases/1.0.X +.. _the history of the 1.0.X branch: https://github.com/django/django/commits/stable/1.0.x diff --git a/docs/releases/1.0.txt b/docs/releases/1.0.txt index e752b02e1b..1e44f57de8 100644 --- a/docs/releases/1.0.txt +++ b/docs/releases/1.0.txt @@ -57,7 +57,7 @@ there. In fact, new documentation is one of our favorite features of Django 1.0, so we might as well start there. First, there's a new documentation site: -* http://docs.djangoproject.com/ +* https://docs.djangoproject.com/ The documentation has been greatly improved, cleaned up, and generally made awesome. There's now dedicated search, indexes, and more. diff --git a/docs/releases/1.1.txt b/docs/releases/1.1.txt index 12940114ed..852644dee4 100644 --- a/docs/releases/1.1.txt +++ b/docs/releases/1.1.txt @@ -101,7 +101,7 @@ If you've been relying on this middleware, the easiest upgrade path is: * Introduce your modified version of ``SetRemoteAddrFromForwardedFor`` as a piece of middleware in your own project. -__ https://code.djangoproject.com/browser/django/trunk/django/middleware/http.py?rev=11000#L33 +__ https://github.com/django/django/blob/91f18400cc0fb37659e2dbaab5484ff2081f1f30/django/middleware/http.py#L33 Names of uploaded files are available later ------------------------------------------- @@ -366,7 +366,7 @@ features: For more details, see the `GeoDjango documentation`_. .. _geodjango: http://geodjango.org/ -.. _spatialite: http://www.gaia-gis.it/spatialite/ +.. _spatialite: http://www.gaia-gis.it/gaia-sins/ .. _geodjango documentation: http://geodjango.org/docs/ Other improvements diff --git a/docs/releases/1.3.txt b/docs/releases/1.3.txt index a2b5447476..772dbdb2e7 100644 --- a/docs/releases/1.3.txt +++ b/docs/releases/1.3.txt @@ -329,7 +329,7 @@ requests. These include: * Support for combining :ref:`F() expressions <query-expressions>` with timedelta values when retrieving or updating database values. -.. _HTTPOnly: http://www.owasp.org/index.php/HTTPOnly +.. _HTTPOnly: https://www.owasp.org/index.php/HTTPOnly .. _backwards-incompatible-changes-1.3: diff --git a/docs/releases/1.4.txt b/docs/releases/1.4.txt index 51766dc2f5..01532cc04c 100644 --- a/docs/releases/1.4.txt +++ b/docs/releases/1.4.txt @@ -37,7 +37,7 @@ Other notable new features in Django 1.4 include: the ability to `bulk insert <#model-objects-bulk-create-in-the-orm>`_ large datasets for improved performance, and `QuerySet.prefetch_related`_, a method to batch-load related objects - in areas where :meth:`~django.db.models.QuerySet.select_related` does't + in areas where :meth:`~django.db.models.QuerySet.select_related` doesn't work. * Some nice security additions, including `improved password hashing`_ @@ -1145,6 +1145,15 @@ field. This was something that should not have worked, and in 1.4 loading such incomplete fixtures will fail. Because fixtures are a raw import, they should explicitly specify all field values, regardless of field options on the model. +Development Server Multithreading +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The development server is now is multithreaded by default. Use the +:djadminopt:`--nothreading` option to disable the use of threading in the +development server:: + + django-admin.py runserver --nothreading + Attributes disabled in markdown when safe mode set ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -1338,4 +1347,3 @@ Versions of Python-Markdown earlier than 2.1 do not support the option to disable attributes. As a security issue, earlier versions of this library will not be supported by the markup contrib app in 1.5 under an accelerated deprecation timeline. - diff --git a/docs/releases/1.5.txt b/docs/releases/1.5.txt index 3e274b5d98..aae8b25e07 100644 --- a/docs/releases/1.5.txt +++ b/docs/releases/1.5.txt @@ -16,7 +16,7 @@ features`_. Python compatibility ==================== -Django 1.5 has dropped support for Python 2.5. Python 2.6 is now the minimum +Django 1.5 has dropped support for Python 2.5. Python 2.6.5 is now the minimum required Python version. Django is tested and supported on Python 2.6 and 2.7. @@ -27,8 +27,9 @@ Django 1.4 until you can upgrade your Python version. Per :doc:`our support poli </internals/release-process>`, Django 1.4 will continue to receive security support until the release of Django 1.6. -Django 1.5 does not run on Jython, because Jython doesn't currently offer any -version compatible with Python 2.6. +Django 1.5 does not run on a Jython final release, because Jython's latest release +doesn't currently support Python 2.6. However, Jython currently does offer an alpha +release featuring 2.7 support. What's new in Django 1.5 ======================== @@ -69,7 +70,7 @@ To make it easier to deal with javascript templates which collide with Django's syntax, you can now use the :ttag:`verbatim` block tag to avoid parsing the tag's content. -Retreival of ``ContentType`` instances associated with proxy models +Retrieval of ``ContentType`` instances associated with proxy models ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The methods :meth:`ContentTypeManager.get_for_model() <django.contrib.contenttypes.models.ContentTypeManager.get_for_model()>` @@ -102,6 +103,14 @@ Django 1.5 also includes several smaller improvements worth noting: * In the localflavor for Canada, "pq" was added to the acceptable codes for Quebec. It's an old abbreviation. +* The :ref:`receiver <connecting-receiver-functions>` decorator is now able to + connect to more than one signal by supplying a list of signals. + +* :meth:`QuerySet.bulk_create() + <django.db.models.query.QuerySet.bulk_create>` has now a batch_size + argument. By default the batch_size is unlimited except for SQLite where + single batch is limited so that 999 parameters per query isn't exceeded. + Backwards incompatible changes in 1.5 ===================================== @@ -164,6 +173,77 @@ number was inside the existing page range. It does check it now and raises an :exc:`InvalidPage` exception when the number is either too low or too high. +Behavior of autocommit database option on PostgreSQL changed +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +PostgreSQL's autocommit option didn't work as advertised previously. It did +work for single transaction block, but after the first block was left the +autocommit behavior was never restored. This bug is now fixed in 1.5. While +this is only a bug fix, it is worth checking your applications behavior if +you are using PostgreSQL together with the autocommit option. + +Session not saved on 500 responses +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Django's session middleware will skip saving the session data if the +response's status code is 500. + +Changes in tests execution +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Some changes have been introduced in the execution of tests that might be +backward-incompatible for some testing setups: + +Database flushing in ``django.test.TransactionTestCase`` +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Previously, the test database was truncated *before* each test run in a +:class:`~django.test.TransactionTestCase`. + +In order to be able to run unit tests in any order and to make sure they are +always isolated from each other, :class:`~django.test.TransactionTestCase` will +now reset the database *after* each test run instead. + +No more implict DB sequences reset +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +:class:`~django.test.TransactionTestCase` tests used to reset primary key +sequences automatically together with the database flushing actions described +above. + +This has been changed so no sequences are implicitly reset. This can cause +:class:`~django.test.TransactionTestCase` tests that depend on hard-coded +primary key values to break. + +The new :attr:`~django.test.TransactionTestCase.reset_sequences` attribute can +be used to force the old behavior for :class:`~django.test.TransactionTestCase` +that might need it. + +Ordering of tests +^^^^^^^^^^^^^^^^^ + +In order to make sure all ``TestCase`` code starts with a clean database, +tests are now executed in the following order: + +* First, all unittests (including :class:`unittest.TestCase`, + :class:`~django.test.SimpleTestCase`, :class:`~django.test.TestCase` and + :class:`~django.test.TransactionTestCase`) are run with no particular ordering + guaranteed nor enforced among them. + +* Then any other tests (e.g. doctests) that may alter the database without + restoring it to its original state are run. + +This should not cause any problems unless you have existing doctests which +assume a :class:`~django.test.TransactionTestCase` executed earlier left some +database state behind or unit tests that rely on some form of state being +preserved after the execution of other tests. Such tests are already very +fragile, and must now be changed to be able to run independently. + +Miscellaneous +~~~~~~~~~~~~~ + +* GeoDjango dropped support for GDAL < 1.5 + Features deprecated in 1.5 ========================== diff --git a/docs/topics/class-based-views/generic-display.txt b/docs/topics/class-based-views/generic-display.txt index 39fb41df04..0d4cb6244d 100644 --- a/docs/topics/class-based-views/generic-display.txt +++ b/docs/topics/class-based-views/generic-display.txt @@ -157,7 +157,7 @@ might look like the following:: That's really all there is to it. All the cool features of generic views come from changing the attributes set on the generic view. The :doc:`generic views reference</ref/class-based-views/index>` documents all the -generic views and their options in detail; the rest of this document will +generic views and their options in detail; the rest of this document will consider some of the common ways you might customize and extend generic views. @@ -220,7 +220,7 @@ more:: def get_context_data(self, **kwargs): # Call the base implementation first to get a context - context = super(PublisherDetailView, self).get_context_data(**kwargs) + context = super(PublisherDetail, self).get_context_data(**kwargs) # Add in a QuerySet of all the books context['book_list'] = Book.objects.all() return context @@ -284,7 +284,7 @@ technique:: from django.views.generic import ListView from books.models import Book - class AcmeBookListView(ListView): + class AcmeBookList(ListView): context_object_name = 'book_list' queryset = Book.objects.filter(publisher__name='Acme Publishing') @@ -361,7 +361,7 @@ use it in the template:: def get_context_data(self, **kwargs): # Call the base implementation first to get a context - context = super(PublisherBookListView, self).get_context_data(**kwargs) + context = super(PublisherBookList, self).get_context_data(**kwargs) # Add in the publisher context['publisher'] = self.publisher return context @@ -397,7 +397,7 @@ custom view:: urlpatterns = patterns('', #... - url(r'^authors/(?P<pk>\\d+)/$', AuthorDetailView.as_view(), name='author-detail'), + url(r'^authors/(?P<pk>\d+)/$', AuthorDetailView.as_view(), name='author-detail'), ) Then we'd write our new view -- ``get_object`` is the method that retrieves the diff --git a/docs/topics/class-based-views/index.txt b/docs/topics/class-based-views/index.txt index bdf649da48..6c2848944c 100644 --- a/docs/topics/class-based-views/index.txt +++ b/docs/topics/class-based-views/index.txt @@ -93,13 +93,13 @@ conversion to JSON once. For example, a simple JSON mixin might look something like this:: import json - from django import http + from django.http import HttpResponse class JSONResponseMixin(object): """ A mixin that can be used to render a JSON response. """ - reponse_class = HTTPResponse + response_class = HttpResponse def render_to_response(self, context, **response_kwargs): """ diff --git a/docs/topics/db/models.txt b/docs/topics/db/models.txt index 4010ff6f9c..ce15dc9535 100644 --- a/docs/topics/db/models.txt +++ b/docs/topics/db/models.txt @@ -384,7 +384,8 @@ Extra fields on many-to-many relationships ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When you're only dealing with simple many-to-many relationships such as -mixing and matching pizzas and toppings, a standard :class:`~django.db.models.ManyToManyField` is all you need. However, sometimes +mixing and matching pizzas and toppings, a standard +:class:`~django.db.models.ManyToManyField` is all you need. However, sometimes you may need to associate data with the relationship between two models. For example, consider the case of an application tracking the musical groups diff --git a/docs/topics/db/transactions.txt b/docs/topics/db/transactions.txt index 76b65b99e0..9928354664 100644 --- a/docs/topics/db/transactions.txt +++ b/docs/topics/db/transactions.txt @@ -54,6 +54,13 @@ The various cache middlewares are an exception: Even when using database caching, Django's cache backend uses its own database cursor (which is mapped to its own database connection internally). +.. note:: + + The ``TransactionMiddleware`` only affects the database aliased + as "default" within your :setting:`DATABASES` setting. If you are using + multiple databases and want transaction control over databases other than + "default", you will need to write your own transaction middleware. + .. _transaction-management-functions: Controlling transaction management in views diff --git a/docs/topics/email.txt b/docs/topics/email.txt index 3a78a83ce5..0cc476e02c 100644 --- a/docs/topics/email.txt +++ b/docs/topics/email.txt @@ -192,7 +192,7 @@ from the request's POST data, sends that to admin@example.com and redirects to # to get proper validation errors. return HttpResponse('Make sure all fields are entered and valid.') -.. _Header injection: http://www.nyphp.org/phundamentals/email_header_injection.php +.. _Header injection: http://www.nyphp.org/phundamentals/8_Preventing-Email-Header-Injection .. _emailmessage-and-smtpconnection: diff --git a/docs/topics/files.txt b/docs/topics/files.txt index 9ab8d5c496..c9b4327941 100644 --- a/docs/topics/files.txt +++ b/docs/topics/files.txt @@ -75,6 +75,29 @@ using a Python built-in ``file`` object:: Now you can use any of the documented attributes and methods of the :class:`~django.core.files.File` class. +Be aware that files created in this way are not automatically closed. +The following approach may be used to close files automatically:: + + >>> from django.core.files import File + + # Create a Python file object using open() and the with statement + >>> with open('/tmp/hello.world', 'w') as f: + >>> myfile = File(f) + >>> for line in myfile: + >>> print line + >>> myfile.closed + True + >>> f.closed + True + +Closing files is especially important when accessing file fields in a loop +over a large number of objects:: If files are not manually closed after +accessing them, the risk of running out of file descriptors may arise. This +may lead to the following error: + + IOError: [Errno 24] Too many open files + + File storage ============ diff --git a/docs/topics/forms/index.txt b/docs/topics/forms/index.txt index b843107871..4693de6c7e 100644 --- a/docs/topics/forms/index.txt +++ b/docs/topics/forms/index.txt @@ -91,6 +91,9 @@ The standard pattern for processing a form in a view looks like this: .. code-block:: python + from django.shortcuts import render + from django.http import HttpResponseRedirect + def contact(request): if request.method == 'POST': # If the form has been submitted... form = ContactForm(request.POST) # A form bound to the POST data diff --git a/docs/topics/forms/modelforms.txt b/docs/topics/forms/modelforms.txt index eb53b177c5..4cfde400a7 100644 --- a/docs/topics/forms/modelforms.txt +++ b/docs/topics/forms/modelforms.txt @@ -877,7 +877,8 @@ of a model. Here's how you can do that:: formset = BookInlineFormSet(request.POST, request.FILES, instance=author) if formset.is_valid(): formset.save() - # Do something. + # Do something. Should generally end with a redirect. For example: + return HttpResponseRedirect(author.get_absolute_url()) else: formset = BookInlineFormSet(instance=author) return render_to_response("manage_books.html", { diff --git a/docs/topics/http/middleware.txt b/docs/topics/http/middleware.txt index a768a3bbd8..fe92bc59a9 100644 --- a/docs/topics/http/middleware.txt +++ b/docs/topics/http/middleware.txt @@ -199,7 +199,8 @@ of caveats: define ``__init__`` as requiring any arguments. * Unlike the ``process_*`` methods which get called once per request, - ``__init__`` gets called only *once*, when the Web server starts up. + ``__init__`` gets called only *once*, when the Web server responds to the + first request. Marking middleware as unused ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/docs/topics/http/sessions.txt b/docs/topics/http/sessions.txt index 20dc61a222..1f55293413 100644 --- a/docs/topics/http/sessions.txt +++ b/docs/topics/http/sessions.txt @@ -423,6 +423,9 @@ cookie will be sent on every request. Similarly, the ``expires`` part of a session cookie is updated each time the session cookie is sent. +.. versionchanged:: 1.5 + The session is not saved if the response's status code is 500. + Browser-length sessions vs. persistent sessions =============================================== @@ -521,7 +524,7 @@ consistently by all browsers. However, when it is honored, it can be a useful way to mitigate the risk of client side script accessing the protected cookie data. -.. _HTTPOnly: http://www.owasp.org/index.php/HTTPOnly +.. _HTTPOnly: https://www.owasp.org/index.php/HTTPOnly SESSION_COOKIE_NAME ------------------- diff --git a/docs/topics/http/shortcuts.txt b/docs/topics/http/shortcuts.txt index 2185d5497f..10be353e80 100644 --- a/docs/topics/http/shortcuts.txt +++ b/docs/topics/http/shortcuts.txt @@ -15,7 +15,7 @@ introduce controlled coupling for convenience's sake. ``render`` ========== -.. function:: render(request, template[, dictionary][, context_instance][, content_type][, status][, current_app]) +.. function:: render(request, template_name[, dictionary][, context_instance][, content_type][, status][, current_app]) .. versionadded:: 1.3 @@ -32,7 +32,7 @@ Required arguments ``request`` The request object used to generate this response. -``template`` +``template_name`` The full name of a template to use or sequence of template names. Optional arguments diff --git a/docs/topics/http/urls.txt b/docs/topics/http/urls.txt index 2310fac413..4e75dfe55f 100644 --- a/docs/topics/http/urls.txt +++ b/docs/topics/http/urls.txt @@ -704,8 +704,8 @@ target each pattern individually by using its name: .. code-block:: html+django - {% url arch-summary 1945 %} - {% url full-archive 2007 %} + {% url 'arch-summary' 1945 %} + {% url 'full-archive' 2007 %} Even though both URL patterns refer to the ``archive`` view here, using the ``name`` parameter to ``url()`` allows you to tell them apart in templates. diff --git a/docs/topics/i18n/timezones.txt b/docs/topics/i18n/timezones.txt index 1d9dd4b3c6..f3bb13ab03 100644 --- a/docs/topics/i18n/timezones.txt +++ b/docs/topics/i18n/timezones.txt @@ -509,7 +509,7 @@ Setup Finally, our calendar system contains interesting traps for computers:: >>> import datetime - >>> def substract_one_year(value): # DON'T DO THAT! + >>> def one_year_before(value): # DON'T DO THAT! ... return value.replace(year=value.year - 1) >>> one_year_before(datetime.datetime(2012, 3, 1, 10, 0)) datetime.datetime(2011, 3, 1, 10, 0) diff --git a/docs/topics/i18n/translation.txt b/docs/topics/i18n/translation.txt index 896ff87744..c912bf9575 100644 --- a/docs/topics/i18n/translation.txt +++ b/docs/topics/i18n/translation.txt @@ -596,7 +596,7 @@ apply. Reverse URL lookups cannot be carried out within the ``blocktrans`` and should be retrieved (and stored) beforehand:: - {% url path.to.view arg arg2 as the_url %} + {% url 'path.to.view' arg arg2 as the_url %} {% blocktrans %} This is a URL: {{ the_url }} {% endblocktrans %} @@ -790,7 +790,7 @@ To use the catalog, just pull in the dynamically generated script like this: .. code-block:: html+django - <script type="text/javascript" src="{% url django.views.i18n.javascript_catalog %}"></script> + <script type="text/javascript" src="{% url 'django.views.i18n.javascript_catalog' %}"></script> This uses reverse URL lookup to find the URL of the JavaScript catalog view. When the catalog is loaded, your JavaScript code can use the standard @@ -890,7 +890,7 @@ prepend the current active language code to all url patterns defined within urlpatterns += i18n_patterns('', url(r'^about/$', 'about.view', name='about'), - url(r'^news/$', include(news_patterns, namespace='news')), + url(r'^news/', include(news_patterns, namespace='news')), ) @@ -945,7 +945,7 @@ URL patterns can also be marked translatable using the urlpatterns += i18n_patterns('', url(_(r'^about/$'), 'about.view', name='about'), - url(_(r'^news/$'), include(news_patterns, namespace='news')), + url(_(r'^news/'), include(news_patterns, namespace='news')), ) @@ -992,7 +992,7 @@ template tag. It enables the given language in the enclosed template section: {% trans "View this category in:" %} {% for lang_code, lang_name in languages %} {% language lang_code %} - <a href="{% url category slug=category.slug %}">{{ lang_name }}</a> + <a href="{% url 'category' slug=category.slug %}">{{ lang_name }}</a> {% endlanguage %} {% endfor %} diff --git a/docs/topics/install.txt b/docs/topics/install.txt index 0cdb8a49e7..a11a44baa1 100644 --- a/docs/topics/install.txt +++ b/docs/topics/install.txt @@ -9,7 +9,7 @@ Install Python Being a Python Web framework, Django requires Python. -It works with any Python version from 2.6 to 2.7 (due to backwards +It works with any Python version from 2.6.5 to 2.7 (due to backwards incompatibilities in Python 3.0, Django does not currently work with Python 3.0; see :doc:`the Django FAQ </faq/install>` for more information on supported Python versions and the 3.0 transition). @@ -62,7 +62,7 @@ for information on how to configure mod_wsgi once you have it installed. If you can't use mod_wsgi for some reason, fear not: Django supports many other -deployment options. One is :doc:`uWSGI </howto/deployment/fastcgi>`; it works +deployment options. One is :doc:`uWSGI </howto/deployment/wsgi/uwsgi>`; it works very well with `nginx`_. Another is :doc:`FastCGI </howto/deployment/fastcgi>`, perfect for using Django with servers other than Apache. Additionally, Django follows the WSGI spec (:pep:`3333`), which allows it to run on a variety of @@ -70,7 +70,7 @@ server platforms. See the `server-arrangements wiki page`_ for specific installation instructions for each platform. .. _Apache: http://httpd.apache.org/ -.. _nginx: http://nginx.net/ +.. _nginx: http://nginx.org/ .. _mod_wsgi: http://code.google.com/p/modwsgi/ .. _server-arrangements wiki page: https://code.djangoproject.com/wiki/ServerArrangements diff --git a/docs/topics/logging.txt b/docs/topics/logging.txt index aa2afba760..a878d42266 100644 --- a/docs/topics/logging.txt +++ b/docs/topics/logging.txt @@ -209,8 +209,8 @@ By default, Django uses the `dictConfig format`_. ``logging.dictConfig`` is a builtin library in Python 2.7. In order to make this library available for users of earlier Python versions, Django includes a copy as part of ``django.utils.log``. - If you have Python 2.7, the system native library will be used; if - you have Python 2.6 or earlier, Django's copy will be used. + If you have Python 2.7 or later, the system native library will be used; if + you have Python 2.6, Django's copy will be used. In order to configure logging, you use :setting:`LOGGING` to define a dictionary of logging settings. These settings describes the loggers, diff --git a/docs/topics/python3.txt b/docs/topics/python3.txt index 974ddb0e88..3f799edac7 100644 --- a/docs/topics/python3.txt +++ b/docs/topics/python3.txt @@ -2,251 +2,136 @@ Python 3 compatibility ====================== -Django 1.5 introduces a compatibility layer that allows the code to be run both -in Python 2 (2.6/2.7) and Python 3 (>= 3.2) (*work in progress*). +Django 1.5 is the first version of Django to support Python 3. The same code +runs both on Python 2 (≥ 2.6.5) and Python 3 (≥ 3.2), thanks to the six_ +compatibility layer and ``unicode_literals``. -This document is not meant as a complete Python 2 to Python 3 migration guide. -There are many existing resources you can read. But we describe some utilities -and guidelines that we recommend you should use when you want to ensure your -code can be run with both Python 2 and 3. +.. _six: http://packages.python.org/six/ -* http://docs.python.org/py3k/howto/pyporting.html -* http://python3porting.com/ +This document is not meant as a Python 2 to Python 3 migration guide. There +are many existing resources, including `Python's official porting guide`_. +Rather, it describes guidelines that apply to Django's code and are +recommended for pluggable apps that run with both Python 2 and 3. -django.utils.py3 -================ +.. _Python's official porting guide: http://docs.python.org/py3k/howto/pyporting.html -Whenever a symbol or module has different semantics or different locations on -Python 2 and Python 3, you can import it from ``django.utils.py3`` where it -will be automatically converted depending on your current Python version. +Syntax requirements +=================== -PY3 ---- - -If you need to know anywhere in your code if you are running Python 3 or a -previous Python 2 version, you can check the ``PY3`` boolean variable:: - - from django.utils.py3 import PY3 +Unicode +------- - if PY3: - # Do stuff Python 3-wise - else: - # Do stuff Python 2-wise - -This should be considered as a last resort solution when it is not possible -to import a compatible name from django.utils.py3, as described in the sections -below. +In Python 3, all strings are considered Unicode by default. The ``unicode`` +type from Python 2 is called ``str`` in Python 3, and ``str`` becomes +``bytes``. -String handling -=============== +You mustn't use the ``u`` prefix before a unicode string literal because it's +a syntax error in Python 3.2. You must prefix byte strings with ``b``. -In Python 3, all strings are considered Unicode strings by default. Byte strings -have to be prefixed with the letter 'b'. To mimic the same behaviour in Python 2, -we recommend you import ``unicode_literals`` from the ``__future__`` library:: +In order to enable the same behavior in Python 2, every module must import +``unicode_literals`` from ``__future__``:: from __future__ import unicode_literals my_string = "This is an unicode literal" my_bytestring = b"This is a bytestring" -Be cautious if you have to slice bytestrings. -See http://docs.python.org/py3k/howto/pyporting.html#bytes-literals - -Different expected strings --------------------------- - -Some method parameters have changed the expected string type of a parameter. -For example, ``strftime`` format parameter expects a bytestring on Python 2 but -a normal (Unicode) string on Python 3. For these cases, ``django.utils.py3`` -provides a ``n()`` function which encodes the string parameter only with -Python 2. - - >>> from __future__ import unicode_literals - >>> from datetime import datetime - - >>> print(datetime.date(2012, 5, 21).strftime(n("%m → %Y"))) - 05 → 2012 - -Renamed types -============= - -Several types are named differently in Python 2 and Python 3. In order to keep -compatibility while using those types, import their corresponding aliases from -``django.utils.py3``. - -=========== ========= ===================== -Python 2 Python 3 django.utils.py3 -=========== ========= ===================== -basestring, str, string_types (tuple) -unicode str text_type -int, long int, integer_types (tuple) -long int long_type -=========== ========= ===================== - -String aliases --------------- - -Code sample:: +Be cautious if you have to `slice bytestrings`_. - if isinstance(foo, basestring): - print("foo is a string") +.. _slice bytestrings: http://docs.python.org/py3k/howto/pyporting.html#bytes-literals - # I want to convert a number to a Unicode string - bar = 45 - bar_string = unicode(bar) +Exceptions +---------- -Should be replaced by:: +When you capture exceptions, use the ``as`` keyword:: - from django.utils.py3 import string_types, text_type - - if isinstance(foo, string_types): - print("foo is a string") - - # I want to convert a number to a Unicode string - bar = 45 - bar_string = text_type(bar) - -No more long type ------------------ - -``long`` and ``int`` types have been unified in Python 3, meaning that ``long`` -is no longer available. ``django.utils.py3`` provides both ``long_type`` and -``integer_types`` aliases. For example: - -.. code-block:: python + try: + ... + except MyException as exc: + ... - # Old Python 2 code - my_var = long(333463247234623) - if isinstance(my_var, (int, long)): - # ... +This older syntax was removed in Python 3:: -Should be replaced by: + try: + ... + except MyException, exc: + ... -.. code-block:: python +The syntax to reraise an exception with a different traceback also changed. +Use :func:`six.reraise`. - from django.utils.py3 import long_type, integer_types - my_var = long_type(333463247234623) - if isinstance(my_var, integer_types): - # ... +.. module: django.utils.six +Writing compatible code with six +================================ -Changed module locations -======================== +six_ is the canonical compatibility library for supporting Python 2 and 3 in +a single codebase. Read its documentation! -The following modules have changed their location in Python 3. Therefore, it is -recommended to import them from the ``django.utils.py3`` compatibility layer: +:mod:`six` is bundled with Django: you can import it as :mod:`django.utils.six`. -=============================== ====================================== ====================== -Python 2 Python3 django.utils.py3 -=============================== ====================================== ====================== -Cookie http.cookies cookies +Here are the most common changes required to write compatible code. -urlparse.urlparse urllib.parse.urlparse urlparse -urlparse.urlunparse urllib.parse.urlunparse urlunparse -urlparse.urljoin urllib.parse.urljoin urljoin -urlparse.urlsplit urllib.parse.urlsplit urlsplit -urlparse.urlunsplit urllib.parse.urlunsplit urlunsplit -urlparse.urldefrag urllib.parse.urldefrag urldefrag -urlparse.parse_qsl urllib.parse.parse_qsl parse_qsl -urllib.quote urllib.parse.quote quote -urllib.unquote urllib.parse.unquote unquote -urllib.quote_plus urllib.parse.quote_plus quote_plus -urllib.unquote_plus urllib.parse.unquote_plus unquote_plus -urllib.urlencode urllib.parse.urlencode urlencode -urllib.urlopen urllib.request.urlopen urlopen -urllib.url2pathname urllib.request.url2pathname url2pathname -urllib.urlretrieve urllib.request.urlretrieve urlretrieve -urllib2 urllib.request urllib2 -urllib2.Request urllib.request.Request Request -urllib2.OpenerDirector urllib.request.OpenerDirector OpenerDirector -urllib2.UnknownHandler urllib.request.UnknownHandler UnknownHandler -urllib2.HTTPHandler urllib.request.HTTPHandler HTTPHandler -urllib2.HTTPSHandler urllib.request.HTTPSHandler HTTPSHandler -urllib2.HTTPDefaultErrorHandler urllib.request.HTTPDefaultErrorHandler HTTPDefaultErrorHandler -urllib2.FTPHandler urllib.request.FTPHandler FTPHandler -urllib2.HTTPError urllib.request.HTTPError HTTPError -urllib2.HTTPErrorProcessor urllib.request.HTTPErrorProcessor HTTPErrorProcessor +String types +------------ -htmlentitydefs.name2codepoint html.entities.name2codepoint name2codepoint -HTMLParser html.parser HTMLParser -cPickle/pickle pickle pickle -thread/dummy_thread _thread/_dummy_thread thread +The ``basestring`` and ``unicode`` types were removed in Python 3, and the +meaning of ``str`` changed. To test these types, use the following idioms:: -os.getcwdu os.getcwd getcwdu -itertools.izip zip zip -sys.maxint sys.maxsize maxsize -unichr chr unichr -xrange range xrange -=============================== ====================================== ====================== + isinstance(myvalue, six.string_types) # replacement for basestring + isinstance(myvalue, six.text_type) # replacement for unicode + isinstance(myvalue, bytes) # replacement for str +Python ≥ 2.6 provides ``bytes`` as an alias for ``str``, so you don't need +:attr:`six.binary_type`. -Ouptut encoding now Unicode -=========================== +``long`` +-------- -If you want to catch stdout/stderr output, the output content is UTF-8 encoded -in Python 2, while it is Unicode strings in Python 3. You can use the OutputIO -stream to capture this output:: +The ``long`` type no longer exists in Python 3. ``1L`` is a syntax error. Use +:data:`six.integer_types` check if a value is an integer or a long:: - from django.utils.py3 import OutputIO + isinstance(myvalue, six.integer_types) # replacement for (int, long) - try: - old_stdout = sys.stdout - out = OutputIO() - sys.stdout = out - # Do stuff which produces standard output - result = out.getvalue() - finally: - sys.stdout = old_stdout +``xrange`` +---------- -Dict iteritems/itervalues/iterkeys -================================== +Import :func:`six.moves.xrange` wherever you use ``xrange``. -The iteritems(), itervalues() and iterkeys() methods of dictionaries do not -exist any more in Python 3, simply because they represent the default items() -values() and keys() behavior in Python 3. Therefore, to keep compatibility, -use similar functions from ``django.utils.py3``:: +Moved modules +------------- - from django.utils.py3 import iteritems, itervalues, iterkeys +Some modules were renamed in Python 3. The :mod:`django.utils.six.moves +<six.moves>` module provides a compatible location to import them. - my_dict = {'a': 21, 'b': 42} - for key, value in iteritems(my_dict): - # ... - for value in itervalues(my_dict): - # ... - for key in iterkeys(my_dict): - # ... +In addition to six' defaults, Django's version provides ``dummy_thread`` as +``_dummy_thread``. -Note that in Python 3, dict.keys(), dict.items() and dict.values() return -"views" instead of lists. Wrap them into list() if you really need their return -values to be in a list. - -http://docs.python.org/release/3.0.1/whatsnew/3.0.html#views-and-iterators-instead-of-lists +PY3 +--- -Metaclass -========= +If you need different code in Python 2 and Python 3, check :data:`six.PY3`:: -The syntax for declaring metaclasses has changed in Python 3. -``django.utils.py3`` offers a compatible way to declare metaclasses:: + if six.PY3: + # do stuff Python 3-wise + else: + # do stuff Python 2-wise - from django.utils.py3 import with_metaclass +This is a last resort solution when :mod:`six` doesn't provide an appropriate +function. - class MyClass(with_metaclass(SubClass1, SubClass2,...)): - # ... +.. module:: django.utils.six -Re-raising exceptions +Customizations of six ===================== -One of the syntaxes to raise exceptions (raise E, V, T) is gone in Python 3. -This is especially used in very specific cases where you want to re-raise a -different exception that the initial one, while keeping the original traceback. -So, instead of:: - - raise Exception, Exception(msg), traceback - -Use:: - - from django.utils.py3 import reraise +The version of six bundled with Django includes a few additional tools: - reraise(Exception, Exception(msg), traceback) +.. function:: iterlists(MultiValueDict) + Returns an iterator over the lists of values of a + :class:`~django.utils.datastructures.MultiValueDict`. This replaces + :meth:`~django.utils.datastructures.MultiValueDict.iterlists()` on Python + 2 and :meth:`~django.utils.datastructures.MultiValueDict.lists()` on + Python 3. diff --git a/docs/topics/signals.txt b/docs/topics/signals.txt index 3ef68316a9..db1bcb03df 100644 --- a/docs/topics/signals.txt +++ b/docs/topics/signals.txt @@ -52,10 +52,10 @@ called when the signal is sent by using the :meth:`.Signal.connect` method: .. method:: Signal.connect(receiver, [sender=None, weak=True, dispatch_uid=None]) - + :param receiver: The callback function which will be connected to this signal. See :ref:`receiver-functions` for more information. - + :param sender: Specifies a particular sender to receive signals from. See :ref:`connecting-to-specific-signals` for more information. @@ -129,10 +129,17 @@ receiver: Now, our ``my_callback`` function will be called each time a request finishes. +Note that ``receiver`` can also take a list of signals to connect a function +to. + .. versionadded:: 1.3 The ``receiver`` decorator was added in Django 1.3. +.. versionchanged:: 1.5 + +The ability to pass a list of signals was added. + .. admonition:: Where should this code live? You can put signal handling and registration code anywhere you like. @@ -182,7 +189,7 @@ Preventing duplicate signals In some circumstances, the module in which you are connecting signals may be imported multiple times. This can cause your receiver function to be registered more than once, and thus called multiples times for a single signal -event. +event. If this behavior is problematic (such as when using signals to send an email whenever a model is saved), pass a unique identifier as @@ -228,7 +235,7 @@ Remember that you're allowed to change this list of arguments at any time, so ge Sending signals --------------- -There are two ways to send send signals in Django. +There are two ways to send signals in Django. .. method:: Signal.send(sender, **kwargs) .. method:: Signal.send_robust(sender, **kwargs) diff --git a/docs/topics/testing.txt b/docs/topics/testing.txt index f7aadd68f3..1f4c970d3e 100644 --- a/docs/topics/testing.txt +++ b/docs/topics/testing.txt @@ -478,6 +478,32 @@ If there are any circular dependencies in the :setting:`TEST_DEPENDENCIES` definition, an ``ImproperlyConfigured`` exception will be raised. +Order in which tests are executed +--------------------------------- + +In order to guarantee that all ``TestCase`` code starts with a clean database, +the Django test runner reorders tests in the following way: + +* First, all unittests (including :class:`unittest.TestCase`, + :class:`~django.test.SimpleTestCase`, :class:`~django.test.TestCase` and + :class:`~django.test.TransactionTestCase`) are run with no particular ordering + guaranteed nor enforced among them. + +* Then any other tests (e.g. doctests) that may alter the database without + restoring it to its original state are run. + +.. versionchanged:: 1.5 + Before Django 1.5, the only guarantee was that + :class:`~django.test.TestCase` tests were always ran first, before any other + tests. + +.. note:: + + The new ordering of tests may reveal unexpected dependencies on test case + ordering. This is the case with doctests that relied on state left in the + database by a given :class:`~django.test.TransactionTestCase` test, they + must be updated to be able to run independently. + Other test conditions --------------------- @@ -1109,8 +1135,11 @@ The following is a simple unit test using the request factory:: response = my_view(request) self.assertEqual(response.status_code, 200) -TestCase --------- +Test cases +---------- + +Provided test case classes +~~~~~~~~~~~~~~~~~~~~~~~~~~ .. currentmodule:: django.test @@ -1124,16 +1153,19 @@ Normal Python unit test classes extend a base class of Hierarchy of Django unit testing classes +TestCase +^^^^^^^^ + .. class:: TestCase() This class provides some additional capabilities that can be useful for testing Web sites. Converting a normal :class:`unittest.TestCase` to a Django :class:`TestCase` is -easy: just change the base class of your test from :class:`unittest.TestCase` to -:class:`django.test.TestCase`. All of the standard Python unit test -functionality will continue to be available, but it will be augmented with some -useful additions, including: +easy: Just change the base class of your test from `'unittest.TestCase'` to +`'django.test.TestCase'`. All of the standard Python unit test functionality +will continue to be available, but it will be augmented with some useful +additions, including: * Automatic loading of fixtures. @@ -1141,11 +1173,18 @@ useful additions, including: * Creates a TestClient instance. -* Django-specific assertions for testing for things - like redirection and form errors. +* Django-specific assertions for testing for things like redirection and form + errors. + +.. versionchanged:: 1.5 + The order in which tests are run has changed. See `Order in which tests are + executed`_. ``TestCase`` inherits from :class:`~django.test.TransactionTestCase`. +TransactionTestCase +^^^^^^^^^^^^^^^^^^^ + .. class:: TransactionTestCase() Django ``TestCase`` classes make use of database transaction facilities, if @@ -1157,38 +1196,66 @@ behavior, you should use a Django ``TransactionTestCase``. ``TransactionTestCase`` and ``TestCase`` are identical except for the manner in which the database is reset to a known state and the ability for test code -to test the effects of commit and rollback. A ``TransactionTestCase`` resets -the database before the test runs by truncating all tables and reloading -initial data. A ``TransactionTestCase`` may call commit and rollback and -observe the effects of these calls on the database. +to test the effects of commit and rollback: -A ``TestCase``, on the other hand, does not truncate tables and reload initial -data at the beginning of a test. Instead, it encloses the test code in a -database transaction that is rolled back at the end of the test. It also -prevents the code under test from issuing any commit or rollback operations -on the database, to ensure that the rollback at the end of the test restores -the database to its initial state. In order to guarantee that all ``TestCase`` -code starts with a clean database, the Django test runner runs all ``TestCase`` -tests first, before any other tests (e.g. doctests) that may alter the -database without restoring it to its original state. +* A ``TransactionTestCase`` resets the database after the test runs by + truncating all tables. A ``TransactionTestCase`` may call commit and rollback + and observe the effects of these calls on the database. -When running on a database that does not support rollback (e.g. MySQL with the -MyISAM storage engine), ``TestCase`` falls back to initializing the database -by truncating tables and reloading initial data. +* A ``TestCase``, on the other hand, does not truncate tables after a test. + Instead, it encloses the test code in a database transaction that is rolled + back at the end of the test. It also prevents the code under test from + issuing any commit or rollback operations on the database, to ensure that the + rollback at the end of the test restores the database to its initial state. -``TransactionTestCase`` inherits from :class:`~django.test.SimpleTestCase`. + When running on a database that does not support rollback (e.g. MySQL with the + MyISAM storage engine), ``TestCase`` falls back to initializing the database + by truncating tables and reloading initial data. .. note:: - The ``TestCase`` use of rollback to un-do the effects of the test code - may reveal previously-undetected errors in test code. For example, - test code that assumes primary keys values will be assigned starting at - one may find that assumption no longer holds true when rollbacks instead - of table truncation are being used to reset the database. Similarly, - the reordering of tests so that all ``TestCase`` classes run first may - reveal unexpected dependencies on test case ordering. In such cases a - quick fix is to switch the ``TestCase`` to a ``TransactionTestCase``. - A better long-term fix, that allows the test to take advantage of the - speed benefit of ``TestCase``, is to fix the underlying test problem. + + .. versionchanged:: 1.5 + + Prior to 1.5, ``TransactionTestCase`` flushed the database tables *before* + each test. In Django 1.5, this is instead done *after* the test has been run. + + When the flush took place before the test, it was guaranteed that primary + key values started at one in :class:`~django.test.TransactionTestCase` + tests. + + Tests should not depend on this behaviour, but for legacy tests that do, the + :attr:`~TransactionTestCase.reset_sequences` attribute can be used until + the test has been properly updated. + +.. versionchanged:: 1.5 + The order in which tests are run has changed. See `Order in which tests are + executed`_. + +``TransactionTestCase`` inherits from :class:`~django.test.SimpleTestCase`. + +.. attribute:: TransactionTestCase.reset_sequences + + .. versionadded:: 1.5 + + Setting ``reset_sequences = True`` on a ``TransactionTestCase`` will make + sure sequences are always reset before the test run:: + + class TestsThatDependsOnPrimaryKeySequences(TransactionTestCase): + reset_sequences = True + + def test_animal_pk(self): + lion = Animal.objects.create(name="lion", sound="roar") + # lion.pk is guaranteed to always be 1 + self.assertEqual(lion.pk, 1) + + Unless you are explicitly testing primary keys sequence numbers, it is + recommended that you do not hard code primary key values in tests. + + Using ``reset_sequences = True`` will slow down the test, since the primary + key reset is an relatively expensive database operation. + +SimpleTestCase +^^^^^^^^^^^^^^ .. class:: SimpleTestCase() @@ -1940,7 +2007,7 @@ out the `full reference`_ for more details. .. _Selenium: http://seleniumhq.org/ .. _selenium package: http://pypi.python.org/pypi/selenium -.. _full reference: http://readthedocs.org/docs/selenium-python/en/latest/api.html +.. _full reference: http://selenium-python.readthedocs.org/en/latest/api.html .. _Firefox: http://www.mozilla.com/firefox/ .. note:: |
