mirror of https://github.com/django/django.git
Alphabetized imports in various docs.
Follow-up ofd97cce3409
and7d3fe36c62
.
This commit is contained in:
parent
1b7d524cfa
commit
35319bf12c
|
@ -105,7 +105,7 @@ template output the commas in a :ttag:`for` loop.
|
||||||
Here's an example, which generates the same CSV file as above::
|
Here's an example, which generates the same CSV file as above::
|
||||||
|
|
||||||
from django.http import HttpResponse
|
from django.http import HttpResponse
|
||||||
from django.template import loader, Context
|
from django.template import Content, loader
|
||||||
|
|
||||||
def some_view(request):
|
def some_view(request):
|
||||||
# Create the HttpResponse object with the appropriate CSV header.
|
# Create the HttpResponse object with the appropriate CSV header.
|
||||||
|
|
|
@ -46,8 +46,8 @@ objects are file-like objects.
|
||||||
|
|
||||||
Here's a "Hello World" example::
|
Here's a "Hello World" example::
|
||||||
|
|
||||||
from reportlab.pdfgen import canvas
|
|
||||||
from django.http import HttpResponse
|
from django.http import HttpResponse
|
||||||
|
from reportlab.pdfgen import canvas
|
||||||
|
|
||||||
def some_view(request):
|
def some_view(request):
|
||||||
# Create the HttpResponse object with the appropriate PDF headers.
|
# Create the HttpResponse object with the appropriate PDF headers.
|
||||||
|
|
|
@ -69,7 +69,7 @@ necessary:
|
||||||
.. code-block:: python
|
.. code-block:: python
|
||||||
|
|
||||||
# Import the models we created from our "news" app
|
# Import the models we created from our "news" app
|
||||||
>>> from news.models import Reporter, Article
|
>>> from news.models import Article, Reporter
|
||||||
|
|
||||||
# No reporters are in the system yet.
|
# No reporters are in the system yet.
|
||||||
>>> Reporter.objects.all()
|
>>> Reporter.objects.all()
|
||||||
|
|
|
@ -383,7 +383,7 @@ the Python import path to your :file:`mysite/settings.py` file.
|
||||||
|
|
||||||
Once you're in the shell, explore the :doc:`database API </topics/db/queries>`::
|
Once you're in the shell, explore the :doc:`database API </topics/db/queries>`::
|
||||||
|
|
||||||
>>> from polls.models import Question, Choice # Import the model classes we just wrote.
|
>>> from polls.models import Choice, Question # Import the model classes we just wrote.
|
||||||
|
|
||||||
# No questions are in the system yet.
|
# No questions are in the system yet.
|
||||||
>>> Question.objects.all()
|
>>> Question.objects.all()
|
||||||
|
@ -469,7 +469,7 @@ the :doc:`time zone support docs </topics/i18n/timezones>`.
|
||||||
Save these changes and start a new Python interactive shell by running
|
Save these changes and start a new Python interactive shell by running
|
||||||
``python manage.py shell`` again::
|
``python manage.py shell`` again::
|
||||||
|
|
||||||
>>> from polls.models import Question, Choice
|
>>> from polls.models import Choice, Question
|
||||||
|
|
||||||
# Make sure our __str__() addition worked.
|
# Make sure our __str__() addition worked.
|
||||||
>>> Question.objects.all()
|
>>> Question.objects.all()
|
||||||
|
|
|
@ -69,8 +69,8 @@ create a real version. Add the following to ``polls/views.py``:
|
||||||
.. snippet::
|
.. snippet::
|
||||||
:filename: polls/views.py
|
:filename: polls/views.py
|
||||||
|
|
||||||
|
from django.http import HttpResponse, HttpResponseRedirect
|
||||||
from django.shortcuts import get_object_or_404, render
|
from django.shortcuts import get_object_or_404, render
|
||||||
from django.http import HttpResponseRedirect, HttpResponse
|
|
||||||
from django.urls import reverse
|
from django.urls import reverse
|
||||||
|
|
||||||
from .models import Choice, Question
|
from .models import Choice, Question
|
||||||
|
@ -262,8 +262,8 @@ views and use Django's generic views instead. To do so, open the
|
||||||
.. snippet::
|
.. snippet::
|
||||||
:filename: polls/views.py
|
:filename: polls/views.py
|
||||||
|
|
||||||
from django.shortcuts import get_object_or_404, render
|
|
||||||
from django.http import HttpResponseRedirect
|
from django.http import HttpResponseRedirect
|
||||||
|
from django.shortcuts import get_object_or_404, render
|
||||||
from django.urls import reverse
|
from django.urls import reverse
|
||||||
from django.views import generic
|
from django.views import generic
|
||||||
|
|
||||||
|
|
|
@ -171,8 +171,8 @@ Put the following in the ``tests.py`` file in the ``polls`` application:
|
||||||
|
|
||||||
import datetime
|
import datetime
|
||||||
|
|
||||||
from django.utils import timezone
|
|
||||||
from django.test import TestCase
|
from django.test import TestCase
|
||||||
|
from django.utils import timezone
|
||||||
|
|
||||||
from .models import Question
|
from .models import Question
|
||||||
|
|
||||||
|
|
|
@ -38,8 +38,8 @@ many projects they are typically the most commonly used views.
|
||||||
|
|
||||||
**Example myapp/views.py**::
|
**Example myapp/views.py**::
|
||||||
|
|
||||||
from django.views.generic.detail import DetailView
|
|
||||||
from django.utils import timezone
|
from django.utils import timezone
|
||||||
|
from django.views.generic.detail import DetailView
|
||||||
|
|
||||||
from articles.models import Article
|
from articles.models import Article
|
||||||
|
|
||||||
|
@ -107,8 +107,8 @@ many projects they are typically the most commonly used views.
|
||||||
|
|
||||||
**Example views.py**::
|
**Example views.py**::
|
||||||
|
|
||||||
from django.views.generic.list import ListView
|
|
||||||
from django.utils import timezone
|
from django.utils import timezone
|
||||||
|
from django.views.generic.list import ListView
|
||||||
|
|
||||||
from articles.models import Article
|
from articles.models import Article
|
||||||
|
|
||||||
|
|
|
@ -15,8 +15,8 @@ editing content:
|
||||||
Some of the examples on this page assume that an ``Author`` model has been
|
Some of the examples on this page assume that an ``Author`` model has been
|
||||||
defined as follows in ``myapp/models.py``::
|
defined as follows in ``myapp/models.py``::
|
||||||
|
|
||||||
from django.urls import reverse
|
|
||||||
from django.db import models
|
from django.db import models
|
||||||
|
from django.urls import reverse
|
||||||
|
|
||||||
class Author(models.Model):
|
class Author(models.Model):
|
||||||
name = models.CharField(max_length=200)
|
name = models.CharField(max_length=200)
|
||||||
|
@ -226,8 +226,8 @@ editing content:
|
||||||
|
|
||||||
**Example myapp/views.py**::
|
**Example myapp/views.py**::
|
||||||
|
|
||||||
from django.views.generic.edit import DeleteView
|
|
||||||
from django.urls import reverse_lazy
|
from django.urls import reverse_lazy
|
||||||
|
from django.views.generic.edit import DeleteView
|
||||||
from myapp.models import Author
|
from myapp.models import Author
|
||||||
|
|
||||||
class AuthorDelete(DeleteView):
|
class AuthorDelete(DeleteView):
|
||||||
|
|
|
@ -220,8 +220,8 @@ example, you might write a simple export function that uses Django's
|
||||||
:doc:`serialization functions </topics/serialization>` to dump some selected
|
:doc:`serialization functions </topics/serialization>` to dump some selected
|
||||||
objects as JSON::
|
objects as JSON::
|
||||||
|
|
||||||
from django.http import HttpResponse
|
|
||||||
from django.core import serializers
|
from django.core import serializers
|
||||||
|
from django.http import HttpResponse
|
||||||
|
|
||||||
def export_as_json(modeladmin, request, queryset):
|
def export_as_json(modeladmin, request, queryset):
|
||||||
response = HttpResponse(content_type="application/json")
|
response = HttpResponse(content_type="application/json")
|
||||||
|
|
|
@ -128,7 +128,7 @@ The ``register`` decorator
|
||||||
argument::
|
argument::
|
||||||
|
|
||||||
from django.contrib import admin
|
from django.contrib import admin
|
||||||
from .models import Author, Reader, Editor
|
from .models import Author, Editor, Reader
|
||||||
from myproject.admin_site import custom_admin_site
|
from myproject.admin_site import custom_admin_site
|
||||||
|
|
||||||
@admin.register(Author, Reader, Editor, site=custom_admin_site)
|
@admin.register(Author, Reader, Editor, site=custom_admin_site)
|
||||||
|
@ -502,12 +502,12 @@ subclass::
|
||||||
that we'd like to use for large text fields instead of the default
|
that we'd like to use for large text fields instead of the default
|
||||||
``<textarea>``. Here's how we'd do that::
|
``<textarea>``. Here's how we'd do that::
|
||||||
|
|
||||||
from django.db import models
|
|
||||||
from django.contrib import admin
|
from django.contrib import admin
|
||||||
|
from django.db import models
|
||||||
|
|
||||||
# Import our custom widget and our model from where they're defined
|
# Import our custom widget and our model from where they're defined
|
||||||
from myapp.widgets import RichTextEditorWidget
|
|
||||||
from myapp.models import MyModel
|
from myapp.models import MyModel
|
||||||
|
from myapp.widgets import RichTextEditorWidget
|
||||||
|
|
||||||
class MyModelAdmin(admin.ModelAdmin):
|
class MyModelAdmin(admin.ModelAdmin):
|
||||||
formfield_overrides = {
|
formfield_overrides = {
|
||||||
|
@ -581,8 +581,8 @@ subclass::
|
||||||
the same as the callable, but ``self`` in this context is the model
|
the same as the callable, but ``self`` in this context is the model
|
||||||
instance. Here's a full model example::
|
instance. Here's a full model example::
|
||||||
|
|
||||||
from django.db import models
|
|
||||||
from django.contrib import admin
|
from django.contrib import admin
|
||||||
|
from django.db import models
|
||||||
|
|
||||||
class Person(models.Model):
|
class Person(models.Model):
|
||||||
name = models.CharField(max_length=50)
|
name = models.CharField(max_length=50)
|
||||||
|
@ -616,8 +616,8 @@ subclass::
|
||||||
|
|
||||||
Here's a full example model::
|
Here's a full example model::
|
||||||
|
|
||||||
from django.db import models
|
|
||||||
from django.contrib import admin
|
from django.contrib import admin
|
||||||
|
from django.db import models
|
||||||
from django.utils.html import format_html
|
from django.utils.html import format_html
|
||||||
|
|
||||||
class Person(models.Model):
|
class Person(models.Model):
|
||||||
|
@ -670,8 +670,8 @@ subclass::
|
||||||
|
|
||||||
Here's a full example model::
|
Here's a full example model::
|
||||||
|
|
||||||
from django.db import models
|
|
||||||
from django.contrib import admin
|
from django.contrib import admin
|
||||||
|
from django.db import models
|
||||||
|
|
||||||
class Person(models.Model):
|
class Person(models.Model):
|
||||||
first_name = models.CharField(max_length=50)
|
first_name = models.CharField(max_length=50)
|
||||||
|
@ -699,8 +699,8 @@ subclass::
|
||||||
|
|
||||||
For example::
|
For example::
|
||||||
|
|
||||||
from django.db import models
|
|
||||||
from django.contrib import admin
|
from django.contrib import admin
|
||||||
|
from django.db import models
|
||||||
from django.utils.html import format_html
|
from django.utils.html import format_html
|
||||||
|
|
||||||
class Person(models.Model):
|
class Person(models.Model):
|
||||||
|
@ -2572,8 +2572,8 @@ Using generic relations as an inline
|
||||||
It is possible to use an inline with generically related objects. Let's say
|
It is possible to use an inline with generically related objects. Let's say
|
||||||
you have the following models::
|
you have the following models::
|
||||||
|
|
||||||
from django.db import models
|
|
||||||
from django.contrib.contenttypes.fields import GenericForeignKey
|
from django.contrib.contenttypes.fields import GenericForeignKey
|
||||||
|
from django.db import models
|
||||||
|
|
||||||
class Image(models.Model):
|
class Image(models.Model):
|
||||||
image = models.ImageField(upload_to="images")
|
image = models.ImageField(upload_to="images")
|
||||||
|
@ -3001,7 +3001,7 @@ respectively::
|
||||||
|
|
||||||
# urls.py
|
# urls.py
|
||||||
from django.urls import path
|
from django.urls import path
|
||||||
from myproject.admin import basic_site, advanced_site
|
from myproject.admin import advanced_site, basic_site
|
||||||
|
|
||||||
urlpatterns = [
|
urlpatterns = [
|
||||||
path('basic-admin/', basic_site.urls),
|
path('basic-admin/', basic_site.urls),
|
||||||
|
@ -3111,7 +3111,7 @@ password box.
|
||||||
|
|
||||||
For example, to get a list of all additions done through the admin::
|
For example, to get a list of all additions done through the admin::
|
||||||
|
|
||||||
from django.contrib.admin.models import LogEntry, ADDITION
|
from django.contrib.admin.models import ADDITION, LogEntry
|
||||||
|
|
||||||
LogEntry.objects.filter(action_flag=ADDITION)
|
LogEntry.objects.filter(action_flag=ADDITION)
|
||||||
|
|
||||||
|
|
|
@ -241,9 +241,9 @@ generic (sometimes called "polymorphic") relationships between models.
|
||||||
|
|
||||||
A simple example is a tagging system, which might look like this::
|
A simple example is a tagging system, which might look like this::
|
||||||
|
|
||||||
from django.db import models
|
|
||||||
from django.contrib.contenttypes.fields import GenericForeignKey
|
from django.contrib.contenttypes.fields import GenericForeignKey
|
||||||
from django.contrib.contenttypes.models import ContentType
|
from django.contrib.contenttypes.models import ContentType
|
||||||
|
from django.db import models
|
||||||
|
|
||||||
class TaggedItem(models.Model):
|
class TaggedItem(models.Model):
|
||||||
tag = models.SlugField()
|
tag = models.SlugField()
|
||||||
|
@ -371,8 +371,8 @@ Reverse generic relations
|
||||||
If you know which models you'll be using most often, you can also add
|
If you know which models you'll be using most often, you can also add
|
||||||
a "reverse" generic relationship to enable an additional API. For example::
|
a "reverse" generic relationship to enable an additional API. For example::
|
||||||
|
|
||||||
from django.db import models
|
|
||||||
from django.contrib.contenttypes.fields import GenericRelation
|
from django.contrib.contenttypes.fields import GenericRelation
|
||||||
|
from django.db import models
|
||||||
|
|
||||||
class Bookmark(models.Model):
|
class Bookmark(models.Model):
|
||||||
url = models.URLField()
|
url = models.URLField()
|
||||||
|
|
|
@ -18,7 +18,7 @@ Example
|
||||||
context of the units. In the example below, two different distance objects are
|
context of the units. In the example below, two different distance objects are
|
||||||
instantiated in units of kilometers (``km``) and miles (``mi``)::
|
instantiated in units of kilometers (``km``) and miles (``mi``)::
|
||||||
|
|
||||||
>>> from django.contrib.gis.measure import Distance, D
|
>>> from django.contrib.gis.measure import D, Distance
|
||||||
>>> d1 = Distance(km=5)
|
>>> d1 = Distance(km=5)
|
||||||
>>> print(d1)
|
>>> print(d1)
|
||||||
5.0 km
|
5.0 km
|
||||||
|
|
|
@ -620,7 +620,7 @@ example, coordinates will be expressed in `EPSG SRID 32140`__,
|
||||||
a coordinate system specific to south Texas **only** and in units of
|
a coordinate system specific to south Texas **only** and in units of
|
||||||
**meters**, not degrees::
|
**meters**, not degrees::
|
||||||
|
|
||||||
>>> from django.contrib.gis.geos import Point, GEOSGeometry
|
>>> from django.contrib.gis.geos import GEOSGeometry, Point
|
||||||
>>> pnt = Point(954158.1, 4215137.1, srid=32140)
|
>>> pnt = Point(954158.1, 4215137.1, srid=32140)
|
||||||
|
|
||||||
Note that ``pnt`` may also be constructed with EWKT, an "extended" form of
|
Note that ``pnt`` may also be constructed with EWKT, an "extended" form of
|
||||||
|
@ -722,7 +722,7 @@ Let's dive right in. Create a file called ``admin.py`` inside the
|
||||||
Next, edit your ``urls.py`` in the ``geodjango`` application folder as follows::
|
Next, edit your ``urls.py`` in the ``geodjango`` application folder as follows::
|
||||||
|
|
||||||
from django.contrib.gis import admin
|
from django.contrib.gis import admin
|
||||||
from django.urls import path, include
|
from django.urls import include, path
|
||||||
|
|
||||||
urlpatterns = [
|
urlpatterns = [
|
||||||
path('admin/', admin.site.urls),
|
path('admin/', admin.site.urls),
|
||||||
|
|
|
@ -26,8 +26,8 @@ Fields
|
||||||
to render any HTML, but it is used to process the submitted data and
|
to render any HTML, but it is used to process the submitted data and
|
||||||
validate it. For example::
|
validate it. For example::
|
||||||
|
|
||||||
>>> from django.contrib.postgres.forms import SimpleArrayField
|
|
||||||
>>> from django import forms
|
>>> from django import forms
|
||||||
|
>>> from django.contrib.postgres.forms import SimpleArrayField
|
||||||
|
|
||||||
>>> class NumberListForm(forms.Form):
|
>>> class NumberListForm(forms.Form):
|
||||||
... numbers = SimpleArrayField(forms.IntegerField())
|
... numbers = SimpleArrayField(forms.IntegerField())
|
||||||
|
@ -48,8 +48,8 @@ Fields
|
||||||
value is used to split the submitted data. It allows you to chain
|
value is used to split the submitted data. It allows you to chain
|
||||||
``SimpleArrayField`` for multidimensional data::
|
``SimpleArrayField`` for multidimensional data::
|
||||||
|
|
||||||
>>> from django.contrib.postgres.forms import SimpleArrayField
|
|
||||||
>>> from django import forms
|
>>> from django import forms
|
||||||
|
>>> from django.contrib.postgres.forms import SimpleArrayField
|
||||||
|
|
||||||
>>> class GridForm(forms.Form):
|
>>> class GridForm(forms.Form):
|
||||||
... places = SimpleArrayField(SimpleArrayField(IntegerField()), delimiter='|')
|
... places = SimpleArrayField(SimpleArrayField(IntegerField()), delimiter='|')
|
||||||
|
|
|
@ -63,8 +63,8 @@ article is associated with one or more sites. In Django model terminology,
|
||||||
that's represented by a :class:`~django.db.models.ManyToManyField` in the
|
that's represented by a :class:`~django.db.models.ManyToManyField` in the
|
||||||
``Article`` model::
|
``Article`` model::
|
||||||
|
|
||||||
from django.db import models
|
|
||||||
from django.contrib.sites.models import Site
|
from django.contrib.sites.models import Site
|
||||||
|
from django.db import models
|
||||||
|
|
||||||
class Article(models.Model):
|
class Article(models.Model):
|
||||||
headline = models.CharField(max_length=200)
|
headline = models.CharField(max_length=200)
|
||||||
|
@ -106,8 +106,8 @@ model in a many-to-one relationship, using
|
||||||
For example, if an article is only allowed on a single site, you'd use a model
|
For example, if an article is only allowed on a single site, you'd use a model
|
||||||
like this::
|
like this::
|
||||||
|
|
||||||
from django.db import models
|
|
||||||
from django.contrib.sites.models import Site
|
from django.contrib.sites.models import Site
|
||||||
|
from django.db import models
|
||||||
|
|
||||||
class Article(models.Model):
|
class Article(models.Model):
|
||||||
headline = models.CharField(max_length=200)
|
headline = models.CharField(max_length=200)
|
||||||
|
@ -218,7 +218,7 @@ different template directories (:setting:`DIRS <TEMPLATES-DIRS>`), you could
|
||||||
simply farm out to the template system like so::
|
simply farm out to the template system like so::
|
||||||
|
|
||||||
from django.core.mail import send_mail
|
from django.core.mail import send_mail
|
||||||
from django.template import loader, Context
|
from django.template import Context, loader
|
||||||
|
|
||||||
def register_for_newsletter(request):
|
def register_for_newsletter(request):
|
||||||
# Check form values, etc., and subscribe the user.
|
# Check form values, etc., and subscribe the user.
|
||||||
|
@ -325,9 +325,9 @@ with the current :class:`~django.contrib.sites.models.Site`.
|
||||||
Use :class:`~django.contrib.sites.managers.CurrentSiteManager` by adding it to
|
Use :class:`~django.contrib.sites.managers.CurrentSiteManager` by adding it to
|
||||||
your model explicitly. For example::
|
your model explicitly. For example::
|
||||||
|
|
||||||
from django.db import models
|
|
||||||
from django.contrib.sites.models import Site
|
from django.contrib.sites.models import Site
|
||||||
from django.contrib.sites.managers import CurrentSiteManager
|
from django.contrib.sites.managers import CurrentSiteManager
|
||||||
|
from django.db import models
|
||||||
|
|
||||||
class Photo(models.Model):
|
class Photo(models.Model):
|
||||||
photo = models.FileField(upload_to='photos')
|
photo = models.FileField(upload_to='photos')
|
||||||
|
@ -362,9 +362,9 @@ a parameter to
|
||||||
model. The following model, which has a field called ``publish_on``,
|
model. The following model, which has a field called ``publish_on``,
|
||||||
demonstrates this::
|
demonstrates this::
|
||||||
|
|
||||||
from django.db import models
|
|
||||||
from django.contrib.sites.models import Site
|
from django.contrib.sites.models import Site
|
||||||
from django.contrib.sites.managers import CurrentSiteManager
|
from django.contrib.sites.managers import CurrentSiteManager
|
||||||
|
from django.db import models
|
||||||
|
|
||||||
class Photo(models.Model):
|
class Photo(models.Model):
|
||||||
photo = models.FileField(upload_to='photos')
|
photo = models.FileField(upload_to='photos')
|
||||||
|
|
|
@ -367,7 +367,7 @@ Here's a full example::
|
||||||
And the accompanying URLconf::
|
And the accompanying URLconf::
|
||||||
|
|
||||||
from django.urls import path
|
from django.urls import path
|
||||||
from myproject.feeds import RssSiteNewsFeed, AtomSiteNewsFeed
|
from myproject.feeds import AtomSiteNewsFeed, RssSiteNewsFeed
|
||||||
|
|
||||||
urlpatterns = [
|
urlpatterns = [
|
||||||
# ...
|
# ...
|
||||||
|
|
|
@ -202,8 +202,8 @@ both is fine, and will incur minimal overhead.
|
||||||
|
|
||||||
Usage::
|
Usage::
|
||||||
|
|
||||||
from django.views.decorators.csrf import csrf_protect
|
|
||||||
from django.shortcuts import render
|
from django.shortcuts import render
|
||||||
|
from django.views.decorators.csrf import csrf_protect
|
||||||
|
|
||||||
@csrf_protect
|
@csrf_protect
|
||||||
def my_view(request):
|
def my_view(request):
|
||||||
|
@ -400,8 +400,8 @@ class-based views<decorating-class-based-views>`.
|
||||||
This decorator marks a view as being exempt from the protection ensured by
|
This decorator marks a view as being exempt from the protection ensured by
|
||||||
the middleware. Example::
|
the middleware. Example::
|
||||||
|
|
||||||
from django.views.decorators.csrf import csrf_exempt
|
|
||||||
from django.http import HttpResponse
|
from django.http import HttpResponse
|
||||||
|
from django.views.decorators.csrf import csrf_exempt
|
||||||
|
|
||||||
@csrf_exempt
|
@csrf_exempt
|
||||||
def my_view(request):
|
def my_view(request):
|
||||||
|
@ -417,8 +417,8 @@ class-based views<decorating-class-based-views>`.
|
||||||
|
|
||||||
Example::
|
Example::
|
||||||
|
|
||||||
from django.views.decorators.csrf import requires_csrf_token
|
|
||||||
from django.shortcuts import render
|
from django.shortcuts import render
|
||||||
|
from django.views.decorators.csrf import requires_csrf_token
|
||||||
|
|
||||||
@requires_csrf_token
|
@requires_csrf_token
|
||||||
def my_view(request):
|
def my_view(request):
|
||||||
|
|
|
@ -229,8 +229,8 @@ defined on the :class:`~django.forms.Field` class itself with the
|
||||||
Simple validators can be used to validate values inside the field, let's have
|
Simple validators can be used to validate values inside the field, let's have
|
||||||
a look at Django's ``SlugField``::
|
a look at Django's ``SlugField``::
|
||||||
|
|
||||||
from django.forms import CharField
|
|
||||||
from django.core import validators
|
from django.core import validators
|
||||||
|
from django.forms import CharField
|
||||||
|
|
||||||
class SlugField(CharField):
|
class SlugField(CharField):
|
||||||
default_validators = [validators.validate_slug]
|
default_validators = [validators.validate_slug]
|
||||||
|
|
|
@ -48,7 +48,7 @@ keyword.
|
||||||
|
|
||||||
Some examples::
|
Some examples::
|
||||||
|
|
||||||
>>> from django.db.models import When, F, Q
|
>>> from django.db.models import F, Q, When
|
||||||
>>> # String arguments refer to fields; the following two examples are equivalent:
|
>>> # String arguments refer to fields; the following two examples are equivalent:
|
||||||
>>> When(account_type=Client.GOLD, then='name')
|
>>> When(account_type=Client.GOLD, then='name')
|
||||||
>>> When(account_type=Client.GOLD, then=F('name'))
|
>>> When(account_type=Client.GOLD, then=F('name'))
|
||||||
|
@ -88,7 +88,7 @@ A simple example::
|
||||||
|
|
||||||
>>>
|
>>>
|
||||||
>>> from datetime import date, timedelta
|
>>> from datetime import date, timedelta
|
||||||
>>> from django.db.models import CharField, Case, Value, When
|
>>> from django.db.models import Case, CharField, Value, When
|
||||||
>>> Client.objects.create(
|
>>> Client.objects.create(
|
||||||
... name='Jane Doe',
|
... name='Jane Doe',
|
||||||
... account_type=Client.REGULAR,
|
... account_type=Client.REGULAR,
|
||||||
|
|
|
@ -979,7 +979,7 @@ than 0. If ``length`` is ``None``, then the rest of the string will be returned.
|
||||||
Usage example::
|
Usage example::
|
||||||
|
|
||||||
>>> # Set the alias to the first 5 characters of the name as lowercase
|
>>> # Set the alias to the first 5 characters of the name as lowercase
|
||||||
>>> from django.db.models.functions import Substr, Lower
|
>>> from django.db.models.functions import Lower, Substr
|
||||||
>>> Author.objects.create(name='Margaret Smith')
|
>>> Author.objects.create(name='Margaret Smith')
|
||||||
>>> Author.objects.update(alias=Lower(Substr('name', 1, 5)))
|
>>> Author.objects.update(alias=Lower(Substr('name', 1, 5)))
|
||||||
1
|
1
|
||||||
|
|
|
@ -26,7 +26,7 @@ Some examples
|
||||||
|
|
||||||
.. code-block:: python
|
.. code-block:: python
|
||||||
|
|
||||||
from django.db.models import F, Count, Value
|
from django.db.models import Count, F, Value
|
||||||
from django.db.models.functions import Length, Upper
|
from django.db.models.functions import Length, Upper
|
||||||
|
|
||||||
# Find companies that have more employees than chairs.
|
# Find companies that have more employees than chairs.
|
||||||
|
@ -252,7 +252,7 @@ is null) after companies that have been contacted::
|
||||||
database functions like ``COALESCE`` and ``LOWER``, or aggregates like ``SUM``.
|
database functions like ``COALESCE`` and ``LOWER``, or aggregates like ``SUM``.
|
||||||
They can be used directly::
|
They can be used directly::
|
||||||
|
|
||||||
from django.db.models import Func, F
|
from django.db.models import F, Func
|
||||||
|
|
||||||
queryset.annotate(field_lower=Func(F('field'), function='LOWER'))
|
queryset.annotate(field_lower=Func(F('field'), function='LOWER'))
|
||||||
|
|
||||||
|
|
|
@ -277,7 +277,7 @@ will be stored in a special error dictionary key,
|
||||||
:data:`~django.core.exceptions.NON_FIELD_ERRORS`. This key is used for errors
|
:data:`~django.core.exceptions.NON_FIELD_ERRORS`. This key is used for errors
|
||||||
that are tied to the entire model instead of to a specific field::
|
that are tied to the entire model instead of to a specific field::
|
||||||
|
|
||||||
from django.core.exceptions import ValidationError, NON_FIELD_ERRORS
|
from django.core.exceptions import NON_FIELD_ERRORS, ValidationError
|
||||||
try:
|
try:
|
||||||
article.full_clean()
|
article.full_clean()
|
||||||
except ValidationError as e:
|
except ValidationError as e:
|
||||||
|
|
|
@ -176,7 +176,7 @@ view would raise a ``Http404`` error before redirecting to it::
|
||||||
|
|
||||||
from urllib.parse import urlparse
|
from urllib.parse import urlparse
|
||||||
from django.urls import resolve
|
from django.urls import resolve
|
||||||
from django.http import HttpResponseRedirect, Http404
|
from django.http import Http404, HttpResponseRedirect
|
||||||
|
|
||||||
def myview(request):
|
def myview(request):
|
||||||
next = request.META.get('HTTP_REFERER', None) or '/'
|
next = request.META.get('HTTP_REFERER', None) or '/'
|
||||||
|
|
|
@ -210,7 +210,7 @@ The default implementation simply adds the object being displayed to the
|
||||||
template, but you can override it to send more::
|
template, but you can override it to send more::
|
||||||
|
|
||||||
from django.views.generic import DetailView
|
from django.views.generic import DetailView
|
||||||
from books.models import Publisher, Book
|
from books.models import Book, Publisher
|
||||||
|
|
||||||
class PublisherDetail(DetailView):
|
class PublisherDetail(DetailView):
|
||||||
|
|
||||||
|
@ -409,8 +409,8 @@ custom view::
|
||||||
Then we'd write our new view -- ``get_object`` is the method that retrieves the
|
Then we'd write our new view -- ``get_object`` is the method that retrieves the
|
||||||
object -- so we simply override it and wrap the call::
|
object -- so we simply override it and wrap the call::
|
||||||
|
|
||||||
from django.views.generic import DetailView
|
|
||||||
from django.utils import timezone
|
from django.utils import timezone
|
||||||
|
from django.views.generic import DetailView
|
||||||
from books.models import Author
|
from books.models import Author
|
||||||
|
|
||||||
class AuthorDetailView(DetailView):
|
class AuthorDetailView(DetailView):
|
||||||
|
|
|
@ -99,8 +99,8 @@ First we need to add :meth:`~django.db.models.Model.get_absolute_url()` to our
|
||||||
.. snippet::
|
.. snippet::
|
||||||
:filename: models.py
|
:filename: models.py
|
||||||
|
|
||||||
from django.urls import reverse
|
|
||||||
from django.db import models
|
from django.db import models
|
||||||
|
from django.urls import reverse
|
||||||
|
|
||||||
class Author(models.Model):
|
class Author(models.Model):
|
||||||
name = models.CharField(max_length=200)
|
name = models.CharField(max_length=200)
|
||||||
|
@ -115,8 +115,8 @@ here; we don't have to write any logic ourselves:
|
||||||
.. snippet::
|
.. snippet::
|
||||||
:filename: views.py
|
:filename: views.py
|
||||||
|
|
||||||
from django.views.generic.edit import CreateView, UpdateView, DeleteView
|
|
||||||
from django.urls import reverse_lazy
|
from django.urls import reverse_lazy
|
||||||
|
from django.views.generic.edit import CreateView, DeleteView, UpdateView
|
||||||
from myapp.models import Author
|
from myapp.models import Author
|
||||||
|
|
||||||
class AuthorCreate(CreateView):
|
class AuthorCreate(CreateView):
|
||||||
|
@ -150,7 +150,7 @@ Finally, we hook these new views into the URLconf:
|
||||||
:filename: urls.py
|
:filename: urls.py
|
||||||
|
|
||||||
from django.urls import path
|
from django.urls import path
|
||||||
from myapp.views import AuthorCreate, AuthorUpdate, AuthorDelete
|
from myapp.views import AuthorCreate, AuthorDelete, AuthorUpdate
|
||||||
|
|
||||||
urlpatterns = [
|
urlpatterns = [
|
||||||
# ...
|
# ...
|
||||||
|
|
|
@ -521,8 +521,8 @@ write our own ``get_context_data()`` to make the
|
||||||
``AuthorInterestForm`` available to the template. We'll skip the
|
``AuthorInterestForm`` available to the template. We'll skip the
|
||||||
``get_object()`` override from before for clarity::
|
``get_object()`` override from before for clarity::
|
||||||
|
|
||||||
from django.views.generic import DetailView
|
|
||||||
from django import forms
|
from django import forms
|
||||||
|
from django.views.generic import DetailView
|
||||||
from books.models import Author
|
from books.models import Author
|
||||||
|
|
||||||
class AuthorInterestForm(forms.Form):
|
class AuthorInterestForm(forms.Form):
|
||||||
|
@ -542,8 +542,8 @@ can find the author we're talking about, and we have to remember to set
|
||||||
``template_name`` to ensure that form errors will render the same
|
``template_name`` to ensure that form errors will render the same
|
||||||
template as ``AuthorDisplay`` is using on ``GET``::
|
template as ``AuthorDisplay`` is using on ``GET``::
|
||||||
|
|
||||||
from django.urls import reverse
|
|
||||||
from django.http import HttpResponseForbidden
|
from django.http import HttpResponseForbidden
|
||||||
|
from django.urls import reverse
|
||||||
from django.views.generic import FormView
|
from django.views.generic import FormView
|
||||||
from django.views.generic.detail import SingleObjectMixin
|
from django.views.generic.detail import SingleObjectMixin
|
||||||
|
|
||||||
|
|
|
@ -277,7 +277,7 @@ For example, we can ask for all publishers, annotated with their respective
|
||||||
total book stock counters (note how we use ``'book'`` to specify the
|
total book stock counters (note how we use ``'book'`` to specify the
|
||||||
``Publisher`` -> ``Book`` reverse foreign key hop)::
|
``Publisher`` -> ``Book`` reverse foreign key hop)::
|
||||||
|
|
||||||
>>> from django.db.models import Count, Min, Sum, Avg
|
>>> from django.db.models import Avg, Count, Min, Sum
|
||||||
>>> Publisher.objects.annotate(Count('book'))
|
>>> Publisher.objects.annotate(Count('book'))
|
||||||
|
|
||||||
(Every ``Publisher`` in the resulting ``QuerySet`` will have an extra attribute
|
(Every ``Publisher`` in the resulting ``QuerySet`` will have an extra attribute
|
||||||
|
@ -324,7 +324,7 @@ constraining the objects for which an annotation is calculated. For example,
|
||||||
you can generate an annotated list of all books that have a title starting
|
you can generate an annotated list of all books that have a title starting
|
||||||
with "Django" using the query::
|
with "Django" using the query::
|
||||||
|
|
||||||
>>> from django.db.models import Count, Avg
|
>>> from django.db.models import Avg, Count
|
||||||
>>> Book.objects.filter(name__startswith="Django").annotate(num_authors=Count('authors'))
|
>>> Book.objects.filter(name__startswith="Django").annotate(num_authors=Count('authors'))
|
||||||
|
|
||||||
When used with an ``aggregate()`` clause, a filter has the effect of
|
When used with an ``aggregate()`` clause, a filter has the effect of
|
||||||
|
@ -578,6 +578,6 @@ For example, if you wanted to calculate the average number of authors per
|
||||||
book you first annotate the set of books with the author count, then
|
book you first annotate the set of books with the author count, then
|
||||||
aggregate that author count, referencing the annotation field::
|
aggregate that author count, referencing the annotation field::
|
||||||
|
|
||||||
>>> from django.db.models import Count, Avg
|
>>> from django.db.models import Avg, Count
|
||||||
>>> Book.objects.annotate(num_authors=Count('authors')).aggregate(Avg('num_authors'))
|
>>> Book.objects.annotate(num_authors=Count('authors')).aggregate(Avg('num_authors'))
|
||||||
{'num_authors__avg': 1.66}
|
{'num_authors__avg': 1.66}
|
||||||
|
|
|
@ -192,7 +192,7 @@ Here's an example view that takes a ``subject``, ``message`` and ``from_email``
|
||||||
from the request's POST data, sends that to admin@example.com and redirects to
|
from the request's POST data, sends that to admin@example.com and redirects to
|
||||||
"/contact/thanks/" when it's done::
|
"/contact/thanks/" when it's done::
|
||||||
|
|
||||||
from django.core.mail import send_mail, BadHeaderError
|
from django.core.mail import BadHeaderError, send_mail
|
||||||
from django.http import HttpResponse, HttpResponseRedirect
|
from django.http import HttpResponse, HttpResponseRedirect
|
||||||
|
|
||||||
def send_email(request):
|
def send_email(request):
|
||||||
|
|
|
@ -140,8 +140,8 @@ the proper storage for that file), you can use file storage systems directly.
|
||||||
You can create an instance of some custom file storage class, or -- often more
|
You can create an instance of some custom file storage class, or -- often more
|
||||||
useful -- you can use the global default storage system::
|
useful -- you can use the global default storage system::
|
||||||
|
|
||||||
>>> from django.core.files.storage import default_storage
|
|
||||||
>>> from django.core.files.base import ContentFile
|
>>> from django.core.files.base import ContentFile
|
||||||
|
>>> from django.core.files.storage import default_storage
|
||||||
|
|
||||||
>>> path = default_storage.save('/path/to/file', ContentFile('new content'))
|
>>> path = default_storage.save('/path/to/file', ContentFile('new content'))
|
||||||
>>> path
|
>>> path
|
||||||
|
@ -169,8 +169,8 @@ which implements basic local filesystem file storage.
|
||||||
For example, the following code will store uploaded files under
|
For example, the following code will store uploaded files under
|
||||||
``/media/photos`` regardless of what your :setting:`MEDIA_ROOT` setting is::
|
``/media/photos`` regardless of what your :setting:`MEDIA_ROOT` setting is::
|
||||||
|
|
||||||
from django.db import models
|
|
||||||
from django.core.files.storage import FileSystemStorage
|
from django.core.files.storage import FileSystemStorage
|
||||||
|
from django.db import models
|
||||||
|
|
||||||
fs = FileSystemStorage(location='/media/photos')
|
fs = FileSystemStorage(location='/media/photos')
|
||||||
|
|
||||||
|
|
|
@ -279,8 +279,8 @@ want it to be published:
|
||||||
.. snippet::
|
.. snippet::
|
||||||
:filename: views.py
|
:filename: views.py
|
||||||
|
|
||||||
from django.shortcuts import render
|
|
||||||
from django.http import HttpResponseRedirect
|
from django.http import HttpResponseRedirect
|
||||||
|
from django.shortcuts import render
|
||||||
|
|
||||||
from .forms import NameForm
|
from .forms import NameForm
|
||||||
|
|
||||||
|
|
|
@ -295,8 +295,8 @@ You can override the error messages from ``NON_FIELD_ERRORS`` raised by model
|
||||||
validation by adding the :data:`~django.core.exceptions.NON_FIELD_ERRORS` key
|
validation by adding the :data:`~django.core.exceptions.NON_FIELD_ERRORS` key
|
||||||
to the ``error_messages`` dictionary of the ``ModelForm``’s inner ``Meta`` class::
|
to the ``error_messages`` dictionary of the ``ModelForm``’s inner ``Meta`` class::
|
||||||
|
|
||||||
from django.forms import ModelForm
|
|
||||||
from django.core.exceptions import NON_FIELD_ERRORS
|
from django.core.exceptions import NON_FIELD_ERRORS
|
||||||
|
from django.forms import ModelForm
|
||||||
|
|
||||||
class ArticleForm(ModelForm):
|
class ArticleForm(ModelForm):
|
||||||
class Meta:
|
class Meta:
|
||||||
|
@ -573,7 +573,7 @@ fields like you would in a regular ``Form``.
|
||||||
If you want to specify a field's validators, you can do so by defining
|
If you want to specify a field's validators, you can do so by defining
|
||||||
the field declaratively and setting its ``validators`` parameter::
|
the field declaratively and setting its ``validators`` parameter::
|
||||||
|
|
||||||
from django.forms import ModelForm, CharField
|
from django.forms import CharField, ModelForm
|
||||||
from myapp.models import Article
|
from myapp.models import Article
|
||||||
|
|
||||||
class ArticleForm(ModelForm):
|
class ArticleForm(ModelForm):
|
||||||
|
|
|
@ -168,7 +168,7 @@ For example::
|
||||||
Register custom converter classes in your URLconf using
|
Register custom converter classes in your URLconf using
|
||||||
:func:`~django.urls.register_converter`::
|
:func:`~django.urls.register_converter`::
|
||||||
|
|
||||||
from django.urls import register_converter, path
|
from django.urls import path, register_converter
|
||||||
|
|
||||||
from . import converters, views
|
from . import converters, views
|
||||||
|
|
||||||
|
@ -614,8 +614,8 @@ You can obtain these in template code by using:
|
||||||
|
|
||||||
Or in Python code::
|
Or in Python code::
|
||||||
|
|
||||||
from django.urls import reverse
|
|
||||||
from django.http import HttpResponseRedirect
|
from django.http import HttpResponseRedirect
|
||||||
|
from django.urls import reverse
|
||||||
|
|
||||||
def redirect_to_year(request):
|
def redirect_to_year(request):
|
||||||
# ...
|
# ...
|
||||||
|
|
|
@ -84,8 +84,8 @@ as a shorter alias, ``_``, to save typing.
|
||||||
In this example, the text ``"Welcome to my site."`` is marked as a translation
|
In this example, the text ``"Welcome to my site."`` is marked as a translation
|
||||||
string::
|
string::
|
||||||
|
|
||||||
from django.utils.translation import gettext as _
|
|
||||||
from django.http import HttpResponse
|
from django.http import HttpResponse
|
||||||
|
from django.utils.translation import gettext as _
|
||||||
|
|
||||||
def my_view(request):
|
def my_view(request):
|
||||||
output = _("Welcome to my site.")
|
output = _("Welcome to my site.")
|
||||||
|
@ -94,8 +94,8 @@ string::
|
||||||
Obviously, you could code this without using the alias. This example is
|
Obviously, you could code this without using the alias. This example is
|
||||||
identical to the previous one::
|
identical to the previous one::
|
||||||
|
|
||||||
from django.utils.translation import gettext
|
|
||||||
from django.http import HttpResponse
|
from django.http import HttpResponse
|
||||||
|
from django.utils.translation import gettext
|
||||||
|
|
||||||
def my_view(request):
|
def my_view(request):
|
||||||
output = gettext("Welcome to my site.")
|
output = gettext("Welcome to my site.")
|
||||||
|
@ -205,8 +205,8 @@ of its value.)
|
||||||
|
|
||||||
For example::
|
For example::
|
||||||
|
|
||||||
from django.utils.translation import ngettext
|
|
||||||
from django.http import HttpResponse
|
from django.http import HttpResponse
|
||||||
|
from django.utils.translation import ngettext
|
||||||
|
|
||||||
def hello_world(request, count):
|
def hello_world(request, count):
|
||||||
page = ngettext(
|
page = ngettext(
|
||||||
|
|
|
@ -86,7 +86,7 @@ show how you can display the results. This example assumes you have a
|
||||||
|
|
||||||
The view function looks like this::
|
The view function looks like this::
|
||||||
|
|
||||||
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
|
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
|
||||||
from django.shortcuts import render
|
from django.shortcuts import render
|
||||||
|
|
||||||
def listing(request):
|
def listing(request):
|
||||||
|
|
|
@ -38,7 +38,7 @@ Example
|
||||||
The following is a simple unit test using the request factory::
|
The following is a simple unit test using the request factory::
|
||||||
|
|
||||||
from django.contrib.auth.models import AnonymousUser, User
|
from django.contrib.auth.models import AnonymousUser, User
|
||||||
from django.test import TestCase, RequestFactory
|
from django.test import RequestFactory, TestCase
|
||||||
|
|
||||||
from .views import MyView, my_view
|
from .views import MyView, my_view
|
||||||
|
|
||||||
|
|
|
@ -1023,7 +1023,7 @@ If you want to use a different ``Client`` class (for example, a subclass
|
||||||
with customized behavior), use the :attr:`~SimpleTestCase.client_class` class
|
with customized behavior), use the :attr:`~SimpleTestCase.client_class` class
|
||||||
attribute::
|
attribute::
|
||||||
|
|
||||||
from django.test import TestCase, Client
|
from django.test import Client, TestCase
|
||||||
|
|
||||||
class MyTestClient(Client):
|
class MyTestClient(Client):
|
||||||
# Specialized methods for your environment
|
# Specialized methods for your environment
|
||||||
|
|
Loading…
Reference in New Issue