mirror of
https://github.com/django/django.git
synced 2025-10-24 06:06:09 +00:00
Refs #34140 -- Corrected rst code-block and various formatting issues in docs.
This commit is contained in:
committed by
Mariusz Felisiak
parent
c67ea79aa9
commit
ba755ca131
@@ -91,11 +91,11 @@ Detailed notes can be found in :ref:`async-queries`, but in short:
|
||||
|
||||
Django also supports some asynchronous model methods that use the database::
|
||||
|
||||
async def make_book(...):
|
||||
async def make_book(*args, **kwargs):
|
||||
book = Book(...)
|
||||
await book.asave(using="secondary")
|
||||
|
||||
async def make_book_with_tags(tags, ...):
|
||||
async def make_book_with_tags(tags, *args, **kwargs):
|
||||
book = await Book.objects.acreate(...)
|
||||
await book.tags.aset(tags)
|
||||
|
||||
@@ -227,13 +227,13 @@ as either a direct wrapper or a decorator::
|
||||
|
||||
from asgiref.sync import async_to_sync
|
||||
|
||||
async def get_data(...):
|
||||
async def get_data():
|
||||
...
|
||||
|
||||
sync_get_data = async_to_sync(get_data)
|
||||
|
||||
@async_to_sync
|
||||
async def get_other_data(...):
|
||||
async def get_other_data():
|
||||
...
|
||||
|
||||
The async function is run in the event loop for the current thread, if one is
|
||||
@@ -264,7 +264,7 @@ as either a direct wrapper or a decorator::
|
||||
async_function = sync_to_async(sensitive_sync_function, thread_sensitive=True)
|
||||
|
||||
@sync_to_async
|
||||
def sync_function(...):
|
||||
def sync_function():
|
||||
...
|
||||
|
||||
Threadlocals and contextvars values are preserved across the boundary in both
|
||||
|
||||
@@ -134,8 +134,10 @@ Authenticating users
|
||||
user = authenticate(username='john', password='secret')
|
||||
if user is not None:
|
||||
# A backend authenticated the credentials
|
||||
...
|
||||
else:
|
||||
# No backend authenticated the credentials
|
||||
...
|
||||
|
||||
``request`` is an optional :class:`~django.http.HttpRequest` which is
|
||||
passed on the ``authenticate()`` method of the authentication backends.
|
||||
@@ -950,7 +952,9 @@ in your own URLconf, for example::
|
||||
path('accounts/', include('django.contrib.auth.urls')),
|
||||
]
|
||||
|
||||
This will include the following URL patterns::
|
||||
This will include the following URL patterns:
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
accounts/login/ [name='login']
|
||||
accounts/logout/ [name='logout']
|
||||
|
||||
@@ -24,7 +24,9 @@ How Django stores passwords
|
||||
Django provides a flexible password storage system and uses PBKDF2 by default.
|
||||
|
||||
The :attr:`~django.contrib.auth.models.User.password` attribute of a
|
||||
:class:`~django.contrib.auth.models.User` object is a string in this format::
|
||||
:class:`~django.contrib.auth.models.User` object is a string in this format:
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
<algorithm>$<iterations>$<salt>$<hash>
|
||||
|
||||
@@ -215,7 +217,8 @@ parameter (use the ``rounds`` parameter when subclassing a bcrypt hasher). For
|
||||
example, to increase the number of iterations used by the default PBKDF2
|
||||
algorithm:
|
||||
|
||||
#. Create a subclass of ``django.contrib.auth.hashers.PBKDF2PasswordHasher``::
|
||||
#. Create a subclass of ``django.contrib.auth.hashers.PBKDF2PasswordHasher``
|
||||
::
|
||||
|
||||
from django.contrib.auth.hashers import PBKDF2PasswordHasher
|
||||
|
||||
|
||||
@@ -18,7 +18,9 @@ That's where caching comes in.
|
||||
|
||||
To cache something is to save the result of an expensive calculation so that
|
||||
you don't have to perform the calculation next time. Here's some pseudocode
|
||||
explaining how this would work for a dynamically generated web page::
|
||||
explaining how this would work for a dynamically generated web page:
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
given a URL, try finding that page in the cache
|
||||
if the page is in the cache:
|
||||
|
||||
@@ -150,7 +150,7 @@ this would lead to incorrect behavior.
|
||||
@etag(etag_func)
|
||||
@last_modified(last_modified_func)
|
||||
def my_view(request):
|
||||
# ...
|
||||
...
|
||||
|
||||
# End of bad code.
|
||||
|
||||
|
||||
@@ -74,9 +74,9 @@ p2 doesn't have an associated restaurant:
|
||||
|
||||
>>> from django.core.exceptions import ObjectDoesNotExist
|
||||
>>> try:
|
||||
>>> p2.restaurant
|
||||
>>> except ObjectDoesNotExist:
|
||||
>>> print("There is no restaurant here.")
|
||||
... p2.restaurant
|
||||
... except ObjectDoesNotExist:
|
||||
... print("There is no restaurant here.")
|
||||
There is no restaurant here.
|
||||
|
||||
You can also use ``hasattr`` to avoid the need for exception catching:
|
||||
|
||||
@@ -675,7 +675,9 @@ Field name restrictions
|
||||
Django places some restrictions on model field names:
|
||||
|
||||
#. A field name cannot be a Python reserved word, because that would result
|
||||
in a Python syntax error. For example::
|
||||
in a Python syntax error. For example:
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
class Example(models.Model):
|
||||
pass = models.IntegerField() # 'pass' is a reserved word!
|
||||
@@ -1221,7 +1223,9 @@ subclass with a :class:`~django.db.models.ManyToManyField`::
|
||||
class Supplier(Place):
|
||||
customers = models.ManyToManyField(Place)
|
||||
|
||||
This results in the error::
|
||||
This results in the error:
|
||||
|
||||
.. code-block:: pytb
|
||||
|
||||
Reverse query name for 'Supplier.customers' clashes with reverse query
|
||||
name for 'Supplier.place_ptr'.
|
||||
|
||||
@@ -1067,7 +1067,7 @@ query for SQL ``NULL``, use :lookup:`isnull`:
|
||||
<Dog: Archie>
|
||||
>>> Dog.objects.filter(data=None)
|
||||
<QuerySet [<Dog: Archie>]>
|
||||
>>> Dog.objects.filter(data=Value(None, JSONField())
|
||||
>>> Dog.objects.filter(data=Value(None, JSONField()))
|
||||
<QuerySet [<Dog: Archie>]>
|
||||
>>> Dog.objects.filter(data__isnull=True)
|
||||
<QuerySet [<Dog: Max>]>
|
||||
@@ -1356,7 +1356,9 @@ For example, this statement yields a single ``Q`` object that represents the
|
||||
|
||||
Q(question__startswith='Who') | Q(question__startswith='What')
|
||||
|
||||
This is equivalent to the following SQL ``WHERE`` clause::
|
||||
This is equivalent to the following SQL ``WHERE`` clause:
|
||||
|
||||
.. code-block: sql
|
||||
|
||||
WHERE question LIKE 'Who%' OR question LIKE 'What%'
|
||||
|
||||
|
||||
@@ -309,7 +309,8 @@ alias::
|
||||
|
||||
from django.db import connections
|
||||
with connections['my_db_alias'].cursor() as cursor:
|
||||
# Your code here...
|
||||
# Your code here
|
||||
...
|
||||
|
||||
By default, the Python DB API will return results without their field names,
|
||||
which means you end up with a ``list`` of values, rather than a ``dict``. At a
|
||||
|
||||
@@ -111,7 +111,7 @@ requirements::
|
||||
css = {
|
||||
'screen': ['pretty.css'],
|
||||
'tv,projector': ['lo_res.css'],
|
||||
'print': ['newspaper.css],
|
||||
'print': ['newspaper.css'],
|
||||
}
|
||||
|
||||
If this last CSS definition were to be rendered, it would become the following HTML:
|
||||
@@ -280,7 +280,7 @@ outputting the complete HTML ``<script>`` or ``<link>`` tag content:
|
||||
>>> from django.utils.html import html_safe
|
||||
>>>
|
||||
>>> @html_safe
|
||||
>>> class JSPath:
|
||||
... class JSPath:
|
||||
... def __str__(self):
|
||||
... return '<script src="https://example.org/asset.js" rel="stylesheet">'
|
||||
|
||||
|
||||
@@ -778,7 +778,9 @@ keyword arguments, or the corresponding attributes on the ``ModelForm`` inner
|
||||
``Meta`` class. Please see the ``ModelForm`` :ref:`modelforms-selecting-fields`
|
||||
documentation.
|
||||
|
||||
... or enable localization for specific fields::
|
||||
... or enable localization for specific fields:
|
||||
|
||||
.. code-block:: pycon
|
||||
|
||||
>>> Form = modelform_factory(Author, form=AuthorForm, localized_fields=["birth_date"])
|
||||
|
||||
|
||||
@@ -127,13 +127,15 @@ You can use the :func:`redirect` function in a number of ways.
|
||||
...
|
||||
return redirect('some-view-name', foo='bar')
|
||||
|
||||
#. By passing a hardcoded URL to redirect to::
|
||||
#. By passing a hardcoded URL to redirect to:
|
||||
::
|
||||
|
||||
def my_view(request):
|
||||
...
|
||||
return redirect('/some/url/')
|
||||
|
||||
This also works with full URLs::
|
||||
This also works with full URLs:
|
||||
::
|
||||
|
||||
def my_view(request):
|
||||
...
|
||||
|
||||
@@ -865,7 +865,9 @@ Secondly, you can include an object that contains embedded namespace data. If
|
||||
you ``include()`` a list of :func:`~django.urls.path` or
|
||||
:func:`~django.urls.re_path` instances, the URLs contained in that object
|
||||
will be added to the global namespace. However, you can also ``include()`` a
|
||||
2-tuple containing::
|
||||
2-tuple containing:
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
(<list of path()/re_path() instances>, <application namespace>)
|
||||
|
||||
|
||||
@@ -262,7 +262,9 @@ In a case like this, consider something like the following::
|
||||
}
|
||||
|
||||
You would get an error when running :djadmin:`django-admin
|
||||
compilemessages <compilemessages>`::
|
||||
compilemessages <compilemessages>`:
|
||||
|
||||
.. code-block: pytb
|
||||
|
||||
a format specification for argument 'name', as in 'msgstr[0]', doesn't exist in 'msgid'
|
||||
|
||||
@@ -1094,7 +1096,9 @@ interface within your Python code::
|
||||
~~~~~~~~~~~~
|
||||
|
||||
The ``ngettext`` function provides an interface to pluralize words and
|
||||
phrases::
|
||||
phrases:
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
const objectCount = 1 // or 0, or 2, or 3, ...
|
||||
const string = ngettext(
|
||||
@@ -1113,7 +1117,9 @@ function supports both positional and named interpolation:
|
||||
* Positional interpolation: ``obj`` contains a JavaScript Array object
|
||||
whose elements values are then sequentially interpolated in their
|
||||
corresponding ``fmt`` placeholders in the same order they appear.
|
||||
For example::
|
||||
For example:
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
const formats = ngettext(
|
||||
'There is %s object. Remaining: %s',
|
||||
@@ -1125,7 +1131,9 @@ function supports both positional and named interpolation:
|
||||
|
||||
* Named interpolation: This mode is selected by passing the optional
|
||||
boolean ``named`` parameter as ``true``. ``obj`` contains a JavaScript
|
||||
object or associative array. For example::
|
||||
object or associative array. For example:
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
const data = {
|
||||
count: 10,
|
||||
@@ -1149,7 +1157,9 @@ to produce proper pluralizations).
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
The ``get_format`` function has access to the configured i18n formatting
|
||||
settings and can retrieve the format string for a given setting name::
|
||||
settings and can retrieve the format string for a given setting name:
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
document.write(get_format('DATE_FORMAT'));
|
||||
// 'N j, Y'
|
||||
@@ -1199,7 +1209,9 @@ translated word::
|
||||
|
||||
The ``npgettext`` function also behaves like the Python variant
|
||||
(:func:`~django.utils.translation.npgettext()`), providing a **pluralized**
|
||||
contextually translated word::
|
||||
contextually translated word:
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
document.write(npgettext('group', 'party', 1));
|
||||
// party
|
||||
@@ -1211,7 +1223,9 @@ contextually translated word::
|
||||
|
||||
The ``pluralidx`` function works in a similar way to the :tfilter:`pluralize`
|
||||
template filter, determining if a given ``count`` should use a plural form of
|
||||
a word or not::
|
||||
a word or not:
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
document.write(pluralidx(0));
|
||||
// true
|
||||
|
||||
@@ -245,7 +245,7 @@ JSON in the following way::
|
||||
"model": "sessions.session",
|
||||
"fields": {
|
||||
"expire_date": "2013-01-16T08:16:59.844Z",
|
||||
...
|
||||
# ...
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
@@ -125,6 +125,7 @@ In your Django apps, use settings by importing the object
|
||||
|
||||
if settings.DEBUG:
|
||||
# Do something
|
||||
...
|
||||
|
||||
Note that ``django.conf.settings`` isn't a module -- it's an object. So
|
||||
importing individual settings is not possible::
|
||||
|
||||
@@ -248,7 +248,9 @@ Use the ``django.test.Client`` class to make requests.
|
||||
>>> c = Client()
|
||||
>>> c.post('/login/', {'name': 'fred', 'passwd': 'secret'})
|
||||
|
||||
...will result in the evaluation of a POST request to this URL::
|
||||
...will result in the evaluation of a POST request to this URL:
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
/login/
|
||||
|
||||
|
||||
Reference in New Issue
Block a user