Refs #23919 -- Replaced super(ClassName, self) with super() in docs.
This commit is contained in:
parent
2d96c027f5
commit
dc165ec8e5
|
@ -307,7 +307,7 @@ class DjangoStandaloneHTMLBuilder(StandaloneHTMLBuilder):
|
||||||
name = 'djangohtml'
|
name = 'djangohtml'
|
||||||
|
|
||||||
def finish(self):
|
def finish(self):
|
||||||
super(DjangoStandaloneHTMLBuilder, self).finish()
|
super().finish()
|
||||||
self.info(bold("writing templatebuiltins.js..."))
|
self.info(bold("writing templatebuiltins.js..."))
|
||||||
xrefs = self.env.domaindata["std"]["objects"]
|
xrefs = self.env.domaindata["std"]["objects"]
|
||||||
templatebuiltins = {
|
templatebuiltins = {
|
||||||
|
|
|
@ -294,7 +294,7 @@ would override ``get_lookup`` with something like::
|
||||||
pass
|
pass
|
||||||
else:
|
else:
|
||||||
return get_coordinate_lookup(dimension)
|
return get_coordinate_lookup(dimension)
|
||||||
return super(CoordinatesField, self).get_lookup(lookup_name)
|
return super().get_lookup(lookup_name)
|
||||||
|
|
||||||
You would then define ``get_coordinate_lookup`` appropriately to return a
|
You would then define ``get_coordinate_lookup`` appropriately to return a
|
||||||
``Lookup`` subclass which handles the relevant value of ``dimension``.
|
``Lookup`` subclass which handles the relevant value of ``dimension``.
|
||||||
|
|
|
@ -274,7 +274,7 @@ the :meth:`~BaseCommand.handle` method must be implemented.
|
||||||
|
|
||||||
class Command(BaseCommand):
|
class Command(BaseCommand):
|
||||||
def __init__(self, *args, **kwargs):
|
def __init__(self, *args, **kwargs):
|
||||||
super(Command, self).__init__(*args, **kwargs)
|
super().__init__(*args, **kwargs)
|
||||||
# ...
|
# ...
|
||||||
|
|
||||||
.. method:: BaseCommand.add_arguments(parser)
|
.. method:: BaseCommand.add_arguments(parser)
|
||||||
|
|
|
@ -168,7 +168,7 @@ behave like any existing field, so we'll subclass directly from
|
||||||
|
|
||||||
def __init__(self, *args, **kwargs):
|
def __init__(self, *args, **kwargs):
|
||||||
kwargs['max_length'] = 104
|
kwargs['max_length'] = 104
|
||||||
super(HandField, self).__init__(*args, **kwargs)
|
super().__init__(*args, **kwargs)
|
||||||
|
|
||||||
Our ``HandField`` accepts most of the standard field options (see the list
|
Our ``HandField`` accepts most of the standard field options (see the list
|
||||||
below), but we ensure it has a fixed length, since it only needs to hold 52
|
below), but we ensure it has a fixed length, since it only needs to hold 52
|
||||||
|
@ -262,10 +262,10 @@ we can drop it from the keyword arguments for readability::
|
||||||
|
|
||||||
def __init__(self, *args, **kwargs):
|
def __init__(self, *args, **kwargs):
|
||||||
kwargs['max_length'] = 104
|
kwargs['max_length'] = 104
|
||||||
super(HandField, self).__init__(*args, **kwargs)
|
super().__init__(*args, **kwargs)
|
||||||
|
|
||||||
def deconstruct(self):
|
def deconstruct(self):
|
||||||
name, path, args, kwargs = super(HandField, self).deconstruct()
|
name, path, args, kwargs = super().deconstruct()
|
||||||
del kwargs["max_length"]
|
del kwargs["max_length"]
|
||||||
return name, path, args, kwargs
|
return name, path, args, kwargs
|
||||||
|
|
||||||
|
@ -279,10 +279,10 @@ into ``kwargs`` yourself::
|
||||||
|
|
||||||
def __init__(self, separator=",", *args, **kwargs):
|
def __init__(self, separator=",", *args, **kwargs):
|
||||||
self.separator = separator
|
self.separator = separator
|
||||||
super(CommaSepField, self).__init__(*args, **kwargs)
|
super().__init__(*args, **kwargs)
|
||||||
|
|
||||||
def deconstruct(self):
|
def deconstruct(self):
|
||||||
name, path, args, kwargs = super(CommaSepField, self).deconstruct()
|
name, path, args, kwargs = super().deconstruct()
|
||||||
# Only include kwarg if it's not the default
|
# Only include kwarg if it's not the default
|
||||||
if self.separator != ",":
|
if self.separator != ",":
|
||||||
kwargs['separator'] = self.separator
|
kwargs['separator'] = self.separator
|
||||||
|
@ -435,7 +435,7 @@ time -- i.e., when the class is instantiated. To do that, just implement
|
||||||
class BetterCharField(models.Field):
|
class BetterCharField(models.Field):
|
||||||
def __init__(self, max_length, *args, **kwargs):
|
def __init__(self, max_length, *args, **kwargs):
|
||||||
self.max_length = max_length
|
self.max_length = max_length
|
||||||
super(BetterCharField, self).__init__(*args, **kwargs)
|
super().__init__(*args, **kwargs)
|
||||||
|
|
||||||
def db_type(self, connection):
|
def db_type(self, connection):
|
||||||
return 'char(%s)' % self.max_length
|
return 'char(%s)' % self.max_length
|
||||||
|
@ -576,7 +576,7 @@ For example, Django uses the following method for its
|
||||||
:class:`BinaryField`::
|
:class:`BinaryField`::
|
||||||
|
|
||||||
def get_db_prep_value(self, value, connection, prepared=False):
|
def get_db_prep_value(self, value, connection, prepared=False):
|
||||||
value = super(BinaryField, self).get_db_prep_value(value, connection, prepared)
|
value = super().get_db_prep_value(value, connection, prepared)
|
||||||
if value is not None:
|
if value is not None:
|
||||||
return connection.Database.Binary(value)
|
return connection.Database.Binary(value)
|
||||||
return value
|
return value
|
||||||
|
@ -633,7 +633,7 @@ as::
|
||||||
# while letting the caller override them.
|
# while letting the caller override them.
|
||||||
defaults = {'form_class': MyFormField}
|
defaults = {'form_class': MyFormField}
|
||||||
defaults.update(kwargs)
|
defaults.update(kwargs)
|
||||||
return super(HandField, self).formfield(**defaults)
|
return super().formfield(**defaults)
|
||||||
|
|
||||||
This assumes we've imported a ``MyFormField`` field class (which has its own
|
This assumes we've imported a ``MyFormField`` field class (which has its own
|
||||||
default widget). This document doesn't cover the details of writing custom form
|
default widget). This document doesn't cover the details of writing custom form
|
||||||
|
|
|
@ -131,7 +131,7 @@ MRO is an acronym for Method Resolution Order.
|
||||||
template_name = "home.html"
|
template_name = "home.html"
|
||||||
|
|
||||||
def get_context_data(self, **kwargs):
|
def get_context_data(self, **kwargs):
|
||||||
context = super(HomePageView, self).get_context_data(**kwargs)
|
context = super().get_context_data(**kwargs)
|
||||||
context['latest_articles'] = Article.objects.all()[:5]
|
context['latest_articles'] = Article.objects.all()[:5]
|
||||||
return context
|
return context
|
||||||
|
|
||||||
|
@ -194,7 +194,7 @@ MRO is an acronym for Method Resolution Order.
|
||||||
def get_redirect_url(self, *args, **kwargs):
|
def get_redirect_url(self, *args, **kwargs):
|
||||||
article = get_object_or_404(Article, pk=kwargs['pk'])
|
article = get_object_or_404(Article, pk=kwargs['pk'])
|
||||||
article.update_counter()
|
article.update_counter()
|
||||||
return super(ArticleCounterRedirectView, self).get_redirect_url(*args, **kwargs)
|
return super().get_redirect_url(*args, **kwargs)
|
||||||
|
|
||||||
**Example urls.py**::
|
**Example urls.py**::
|
||||||
|
|
||||||
|
|
|
@ -48,7 +48,7 @@ many projects they are typically the most commonly used views.
|
||||||
model = Article
|
model = Article
|
||||||
|
|
||||||
def get_context_data(self, **kwargs):
|
def get_context_data(self, **kwargs):
|
||||||
context = super(ArticleDetailView, self).get_context_data(**kwargs)
|
context = super().get_context_data(**kwargs)
|
||||||
context['now'] = timezone.now()
|
context['now'] = timezone.now()
|
||||||
return context
|
return context
|
||||||
|
|
||||||
|
@ -117,7 +117,7 @@ many projects they are typically the most commonly used views.
|
||||||
model = Article
|
model = Article
|
||||||
|
|
||||||
def get_context_data(self, **kwargs):
|
def get_context_data(self, **kwargs):
|
||||||
context = super(ArticleListView, self).get_context_data(**kwargs)
|
context = super().get_context_data(**kwargs)
|
||||||
context['now'] = timezone.now()
|
context['now'] = timezone.now()
|
||||||
return context
|
return context
|
||||||
|
|
||||||
|
|
|
@ -68,7 +68,7 @@ editing content:
|
||||||
# This method is called when valid form data has been POSTed.
|
# This method is called when valid form data has been POSTed.
|
||||||
# It should return an HttpResponse.
|
# It should return an HttpResponse.
|
||||||
form.send_email()
|
form.send_email()
|
||||||
return super(ContactView, self).form_valid(form)
|
return super().form_valid(form)
|
||||||
|
|
||||||
**Example myapp/contact.html**:
|
**Example myapp/contact.html**:
|
||||||
|
|
||||||
|
|
|
@ -15,7 +15,7 @@ Simple mixins
|
||||||
arguments provided will make up the returned context. Example usage::
|
arguments provided will make up the returned context. Example usage::
|
||||||
|
|
||||||
def get_context_data(self, **kwargs):
|
def get_context_data(self, **kwargs):
|
||||||
context = super(RandomNumberView, self).get_context_data(**kwargs)
|
context = super().get_context_data(**kwargs)
|
||||||
context['number'] = random.randrange(1, 100)
|
context['number'] = random.randrange(1, 100)
|
||||||
return context
|
return context
|
||||||
|
|
||||||
|
|
|
@ -351,7 +351,7 @@ Conditionally enabling or disabling actions
|
||||||
...
|
...
|
||||||
|
|
||||||
def get_actions(self, request):
|
def get_actions(self, request):
|
||||||
actions = super(MyModelAdmin, self).get_actions(request)
|
actions = super().get_actions(request)
|
||||||
if request.user.username[0].upper() != 'J':
|
if request.user.username[0].upper() != 'J':
|
||||||
if 'delete_selected' in actions:
|
if 'delete_selected' in actions:
|
||||||
del actions['delete_selected']
|
del actions['delete_selected']
|
||||||
|
|
|
@ -910,11 +910,11 @@ subclass::
|
||||||
|
|
||||||
def lookups(self, request, model_admin):
|
def lookups(self, request, model_admin):
|
||||||
if request.user.is_superuser:
|
if request.user.is_superuser:
|
||||||
return super(AuthDecadeBornListFilter, self).lookups(request, model_admin)
|
return super().lookups(request, model_admin)
|
||||||
|
|
||||||
def queryset(self, request, queryset):
|
def queryset(self, request, queryset):
|
||||||
if request.user.is_superuser:
|
if request.user.is_superuser:
|
||||||
return super(AuthDecadeBornListFilter, self).queryset(request, queryset)
|
return super().queryset(request, queryset)
|
||||||
|
|
||||||
Also as a convenience, the ``ModelAdmin`` object is passed to
|
Also as a convenience, the ``ModelAdmin`` object is passed to
|
||||||
the ``lookups`` method, for example if you want to base the
|
the ``lookups`` method, for example if you want to base the
|
||||||
|
@ -1342,7 +1342,7 @@ templates used by the :class:`ModelAdmin` views:
|
||||||
class ArticleAdmin(admin.ModelAdmin):
|
class ArticleAdmin(admin.ModelAdmin):
|
||||||
def save_model(self, request, obj, form, change):
|
def save_model(self, request, obj, form, change):
|
||||||
obj.user = request.user
|
obj.user = request.user
|
||||||
super(ArticleAdmin, self).save_model(request, obj, form, change)
|
super().save_model(request, obj, form, change)
|
||||||
|
|
||||||
.. method:: ModelAdmin.delete_model(request, obj)
|
.. method:: ModelAdmin.delete_model(request, obj)
|
||||||
|
|
||||||
|
@ -1409,7 +1409,7 @@ templates used by the :class:`ModelAdmin` views:
|
||||||
search_fields = ('name',)
|
search_fields = ('name',)
|
||||||
|
|
||||||
def get_search_results(self, request, queryset, search_term):
|
def get_search_results(self, request, queryset, search_term):
|
||||||
queryset, use_distinct = super(PersonAdmin, self).get_search_results(request, queryset, search_term)
|
queryset, use_distinct = super().get_search_results(request, queryset, search_term)
|
||||||
try:
|
try:
|
||||||
search_term_as_int = int(search_term)
|
search_term_as_int = int(search_term)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
|
@ -1526,7 +1526,7 @@ templates used by the :class:`ModelAdmin` views:
|
||||||
|
|
||||||
class MyModelAdmin(admin.ModelAdmin):
|
class MyModelAdmin(admin.ModelAdmin):
|
||||||
def get_urls(self):
|
def get_urls(self):
|
||||||
urls = super(MyModelAdmin, self).get_urls()
|
urls = super().get_urls()
|
||||||
my_urls = [
|
my_urls = [
|
||||||
url(r'^my_view/$', self.my_view),
|
url(r'^my_view/$', self.my_view),
|
||||||
]
|
]
|
||||||
|
@ -1578,7 +1578,7 @@ templates used by the :class:`ModelAdmin` views:
|
||||||
|
|
||||||
class MyModelAdmin(admin.ModelAdmin):
|
class MyModelAdmin(admin.ModelAdmin):
|
||||||
def get_urls(self):
|
def get_urls(self):
|
||||||
urls = super(MyModelAdmin, self).get_urls()
|
urls = super().get_urls()
|
||||||
my_urls = [
|
my_urls = [
|
||||||
url(r'^my_view/$', self.admin_site.admin_view(self.my_view))
|
url(r'^my_view/$', self.admin_site.admin_view(self.my_view))
|
||||||
]
|
]
|
||||||
|
@ -1615,7 +1615,7 @@ templates used by the :class:`ModelAdmin` views:
|
||||||
def get_form(self, request, obj=None, **kwargs):
|
def get_form(self, request, obj=None, **kwargs):
|
||||||
if request.user.is_superuser:
|
if request.user.is_superuser:
|
||||||
kwargs['form'] = MySuperuserForm
|
kwargs['form'] = MySuperuserForm
|
||||||
return super(MyModelAdmin, self).get_form(request, obj, **kwargs)
|
return super().get_form(request, obj, **kwargs)
|
||||||
|
|
||||||
You may also simply return a custom :class:`~django.forms.ModelForm` class
|
You may also simply return a custom :class:`~django.forms.ModelForm` class
|
||||||
directly.
|
directly.
|
||||||
|
@ -1648,7 +1648,7 @@ templates used by the :class:`ModelAdmin` views:
|
||||||
def formfield_for_foreignkey(self, db_field, request, **kwargs):
|
def formfield_for_foreignkey(self, db_field, request, **kwargs):
|
||||||
if db_field.name == "car":
|
if db_field.name == "car":
|
||||||
kwargs["queryset"] = Car.objects.filter(owner=request.user)
|
kwargs["queryset"] = Car.objects.filter(owner=request.user)
|
||||||
return super(MyModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
|
return super().formfield_for_foreignkey(db_field, request, **kwargs)
|
||||||
|
|
||||||
This uses the ``HttpRequest`` instance to filter the ``Car`` foreign key
|
This uses the ``HttpRequest`` instance to filter the ``Car`` foreign key
|
||||||
field to only display the cars owned by the ``User`` instance.
|
field to only display the cars owned by the ``User`` instance.
|
||||||
|
@ -1666,7 +1666,7 @@ templates used by the :class:`ModelAdmin` views:
|
||||||
def formfield_for_manytomany(self, db_field, request, **kwargs):
|
def formfield_for_manytomany(self, db_field, request, **kwargs):
|
||||||
if db_field.name == "cars":
|
if db_field.name == "cars":
|
||||||
kwargs["queryset"] = Car.objects.filter(owner=request.user)
|
kwargs["queryset"] = Car.objects.filter(owner=request.user)
|
||||||
return super(MyModelAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)
|
return super().formfield_for_manytomany(db_field, request, **kwargs)
|
||||||
|
|
||||||
.. method:: ModelAdmin.formfield_for_choice_field(db_field, request, **kwargs)
|
.. method:: ModelAdmin.formfield_for_choice_field(db_field, request, **kwargs)
|
||||||
|
|
||||||
|
@ -1685,7 +1685,7 @@ templates used by the :class:`ModelAdmin` views:
|
||||||
)
|
)
|
||||||
if request.user.is_superuser:
|
if request.user.is_superuser:
|
||||||
kwargs['choices'] += (('ready', 'Ready for deployment'),)
|
kwargs['choices'] += (('ready', 'Ready for deployment'),)
|
||||||
return super(MyModelAdmin, self).formfield_for_choice_field(db_field, request, **kwargs)
|
return super().formfield_for_choice_field(db_field, request, **kwargs)
|
||||||
|
|
||||||
.. admonition:: Note
|
.. admonition:: Note
|
||||||
|
|
||||||
|
@ -1740,7 +1740,7 @@ templates used by the :class:`ModelAdmin` views:
|
||||||
class MyModelAdmin(admin.ModelAdmin):
|
class MyModelAdmin(admin.ModelAdmin):
|
||||||
def get_changelist_formset(self, request, **kwargs):
|
def get_changelist_formset(self, request, **kwargs):
|
||||||
kwargs['formset'] = MyAdminFormSet
|
kwargs['formset'] = MyAdminFormSet
|
||||||
return super(MyModelAdmin, self).get_changelist_formset(request, **kwargs)
|
return super().get_changelist_formset(request, **kwargs)
|
||||||
|
|
||||||
.. method:: ModelAdmin.has_add_permission(request)
|
.. method:: ModelAdmin.has_add_permission(request)
|
||||||
|
|
||||||
|
@ -1783,7 +1783,7 @@ templates used by the :class:`ModelAdmin` views:
|
||||||
|
|
||||||
class MyModelAdmin(admin.ModelAdmin):
|
class MyModelAdmin(admin.ModelAdmin):
|
||||||
def get_queryset(self, request):
|
def get_queryset(self, request):
|
||||||
qs = super(MyModelAdmin, self).get_queryset(request)
|
qs = super().get_queryset(request)
|
||||||
if request.user.is_superuser:
|
if request.user.is_superuser:
|
||||||
return qs
|
return qs
|
||||||
return qs.filter(author=request.user)
|
return qs.filter(author=request.user)
|
||||||
|
@ -1902,7 +1902,7 @@ provided some extra mapping data that would not otherwise be available::
|
||||||
def change_view(self, request, object_id, form_url='', extra_context=None):
|
def change_view(self, request, object_id, form_url='', extra_context=None):
|
||||||
extra_context = extra_context or {}
|
extra_context = extra_context or {}
|
||||||
extra_context['osm_data'] = self.get_osm_info()
|
extra_context['osm_data'] = self.get_osm_info()
|
||||||
return super(MyModelAdmin, self).change_view(
|
return super().change_view(
|
||||||
request, object_id, form_url, extra_context=extra_context,
|
request, object_id, form_url, extra_context=extra_context,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
|
@ -509,7 +509,7 @@ method::
|
||||||
class Entry(models.Model):
|
class Entry(models.Model):
|
||||||
# ...
|
# ...
|
||||||
def save(self, force_insert=False, force_update=False):
|
def save(self, force_insert=False, force_update=False):
|
||||||
super(Entry, self).save(force_insert, force_update)
|
super().save(force_insert, force_update)
|
||||||
try:
|
try:
|
||||||
ping_google()
|
ping_google()
|
||||||
except Exception:
|
except Exception:
|
||||||
|
|
|
@ -79,7 +79,7 @@ respectively. For example::
|
||||||
def __init__(self, *args, **kwargs):
|
def __init__(self, *args, **kwargs):
|
||||||
kwargs['file_permissions_mode'] = 0o640
|
kwargs['file_permissions_mode'] = 0o640
|
||||||
kwargs['directory_permissions_mode'] = 0o760
|
kwargs['directory_permissions_mode'] = 0o760
|
||||||
super(MyStaticFilesStorage, self).__init__(*args, **kwargs)
|
super().__init__(*args, **kwargs)
|
||||||
|
|
||||||
Then set the :setting:`STATICFILES_STORAGE` setting to
|
Then set the :setting:`STATICFILES_STORAGE` setting to
|
||||||
``'path.to.MyStaticFilesStorage'``.
|
``'path.to.MyStaticFilesStorage'``.
|
||||||
|
|
|
@ -155,7 +155,7 @@ into those elements.
|
||||||
return Article.objects.order_by('-pub_date')[:5]
|
return Article.objects.order_by('-pub_date')[:5]
|
||||||
|
|
||||||
def get_context_data(self, **kwargs):
|
def get_context_data(self, **kwargs):
|
||||||
context = super(ArticlesFeed, self).get_context_data(**kwargs)
|
context = super().get_context_data(**kwargs)
|
||||||
context['foo'] = 'bar'
|
context['foo'] = 'bar'
|
||||||
return context
|
return context
|
||||||
|
|
||||||
|
@ -1057,12 +1057,12 @@ For example, you might start implementing an iTunes RSS feed generator like so::
|
||||||
|
|
||||||
class iTunesFeed(Rss201rev2Feed):
|
class iTunesFeed(Rss201rev2Feed):
|
||||||
def root_attributes(self):
|
def root_attributes(self):
|
||||||
attrs = super(iTunesFeed, self).root_attributes()
|
attrs = super().root_attributes()
|
||||||
attrs['xmlns:itunes'] = 'http://www.itunes.com/dtds/podcast-1.0.dtd'
|
attrs['xmlns:itunes'] = 'http://www.itunes.com/dtds/podcast-1.0.dtd'
|
||||||
return attrs
|
return attrs
|
||||||
|
|
||||||
def add_root_elements(self, handler):
|
def add_root_elements(self, handler):
|
||||||
super(iTunesFeed, self).add_root_elements(handler)
|
super().add_root_elements(handler)
|
||||||
handler.addQuickElement('itunes:explicit', 'clean')
|
handler.addQuickElement('itunes:explicit', 'clean')
|
||||||
|
|
||||||
Obviously there's a lot more work to be done for a complete custom feed class,
|
Obviously there's a lot more work to be done for a complete custom feed class,
|
||||||
|
|
|
@ -1029,7 +1029,7 @@ Slightly complex built-in ``Field`` classes
|
||||||
required=False,
|
required=False,
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
super(PhoneField, self).__init__(
|
super().__init__(
|
||||||
error_messages=error_messages, fields=fields,
|
error_messages=error_messages, fields=fields,
|
||||||
require_all_fields=False, *args, **kwargs
|
require_all_fields=False, *args, **kwargs
|
||||||
)
|
)
|
||||||
|
@ -1100,7 +1100,7 @@ method::
|
||||||
foo_select = forms.ModelMultipleChoiceField(queryset=None)
|
foo_select = forms.ModelMultipleChoiceField(queryset=None)
|
||||||
|
|
||||||
def __init__(self, *args, **kwargs):
|
def __init__(self, *args, **kwargs):
|
||||||
super(FooMultipleChoiceForm, self).__init__(*args, **kwargs)
|
super().__init__(*args, **kwargs)
|
||||||
self.fields['foo_select'].queryset = ...
|
self.fields['foo_select'].queryset = ...
|
||||||
|
|
||||||
``ModelChoiceField``
|
``ModelChoiceField``
|
||||||
|
|
|
@ -272,7 +272,7 @@ containing comma-separated email addresses. The full class looks like this::
|
||||||
def validate(self, value):
|
def validate(self, value):
|
||||||
"""Check if value consists only of valid emails."""
|
"""Check if value consists only of valid emails."""
|
||||||
# Use the parent's handling of required fields, etc.
|
# Use the parent's handling of required fields, etc.
|
||||||
super(MultiEmailField, self).validate(value)
|
super().validate(value)
|
||||||
for email in value:
|
for email in value:
|
||||||
validate_email(email)
|
validate_email(email)
|
||||||
|
|
||||||
|
@ -352,7 +352,7 @@ example::
|
||||||
...
|
...
|
||||||
|
|
||||||
def clean(self):
|
def clean(self):
|
||||||
cleaned_data = super(ContactForm, self).clean()
|
cleaned_data = super().clean()
|
||||||
cc_myself = cleaned_data.get("cc_myself")
|
cc_myself = cleaned_data.get("cc_myself")
|
||||||
subject = cleaned_data.get("subject")
|
subject = cleaned_data.get("subject")
|
||||||
|
|
||||||
|
@ -367,14 +367,14 @@ example::
|
||||||
In this code, if the validation error is raised, the form will display an
|
In this code, if the validation error is raised, the form will display an
|
||||||
error message at the top of the form (normally) describing the problem.
|
error message at the top of the form (normally) describing the problem.
|
||||||
|
|
||||||
The call to ``super(ContactForm, self).clean()`` in the example code ensures
|
The call to ``super().clean()`` in the example code ensures that any validation
|
||||||
that any validation logic in parent classes is maintained. If your form
|
logic in parent classes is maintained. If your form inherits another that
|
||||||
inherits another that doesn't return a ``cleaned_data`` dictionary in its
|
doesn't return a ``cleaned_data`` dictionary in its ``clean()`` method (doing
|
||||||
``clean()`` method (doing so is optional), then don't assign ``cleaned_data``
|
so is optional), then don't assign ``cleaned_data`` to the result of the
|
||||||
to the result of the ``super()`` call and use ``self.cleaned_data`` instead::
|
``super()`` call and use ``self.cleaned_data`` instead::
|
||||||
|
|
||||||
def clean(self):
|
def clean(self):
|
||||||
super(ContactForm, self).clean()
|
super().clean()
|
||||||
cc_myself = self.cleaned_data.get("cc_myself")
|
cc_myself = self.cleaned_data.get("cc_myself")
|
||||||
...
|
...
|
||||||
|
|
||||||
|
@ -393,7 +393,7 @@ work out what works effectively in your particular situation. Our new code
|
||||||
...
|
...
|
||||||
|
|
||||||
def clean(self):
|
def clean(self):
|
||||||
cleaned_data = super(ContactForm, self).clean()
|
cleaned_data = super().clean()
|
||||||
cc_myself = cleaned_data.get("cc_myself")
|
cc_myself = cleaned_data.get("cc_myself")
|
||||||
subject = cleaned_data.get("subject")
|
subject = cleaned_data.get("subject")
|
||||||
|
|
||||||
|
|
|
@ -410,7 +410,7 @@ foundation for custom widgets.
|
||||||
widgets.Select(attrs=attrs, choices=months),
|
widgets.Select(attrs=attrs, choices=months),
|
||||||
widgets.Select(attrs=attrs, choices=years),
|
widgets.Select(attrs=attrs, choices=years),
|
||||||
)
|
)
|
||||||
super(DateSelectorWidget, self).__init__(_widgets, attrs)
|
super().__init__(_widgets, attrs)
|
||||||
|
|
||||||
def decompress(self, value):
|
def decompress(self, value):
|
||||||
if value:
|
if value:
|
||||||
|
|
|
@ -300,7 +300,7 @@ The ``Func`` API is as follows:
|
||||||
...
|
...
|
||||||
|
|
||||||
def as_mysql(self, compiler, connection):
|
def as_mysql(self, compiler, connection):
|
||||||
return super(ConcatPair, self).as_sql(
|
return super().as_sql(
|
||||||
compiler, connection,
|
compiler, connection,
|
||||||
function='CONCAT_WS',
|
function='CONCAT_WS',
|
||||||
template="%(function)s('', %(expressions)s)",
|
template="%(function)s('', %(expressions)s)",
|
||||||
|
@ -388,7 +388,7 @@ SQL that is generated. Here's a brief example::
|
||||||
template = '%(function)s(%(distinct)s%(expressions)s)'
|
template = '%(function)s(%(distinct)s%(expressions)s)'
|
||||||
|
|
||||||
def __init__(self, expression, distinct=False, **extra):
|
def __init__(self, expression, distinct=False, **extra):
|
||||||
super(Count, self).__init__(
|
super().__init__(
|
||||||
expression,
|
expression,
|
||||||
distinct='DISTINCT ' if distinct else '',
|
distinct='DISTINCT ' if distinct else '',
|
||||||
output_field=IntegerField(),
|
output_field=IntegerField(),
|
||||||
|
@ -776,7 +776,7 @@ an ``__init__()`` method to set some attributes::
|
||||||
template = 'COALESCE( %(expressions)s )'
|
template = 'COALESCE( %(expressions)s )'
|
||||||
|
|
||||||
def __init__(self, expressions, output_field):
|
def __init__(self, expressions, output_field):
|
||||||
super(Coalesce, self).__init__(output_field=output_field)
|
super().__init__(output_field=output_field)
|
||||||
if len(expressions) < 2:
|
if len(expressions) < 2:
|
||||||
raise ValueError('expressions must have at least 2 elements')
|
raise ValueError('expressions must have at least 2 elements')
|
||||||
for expression in expressions:
|
for expression in expressions:
|
||||||
|
|
|
@ -113,7 +113,7 @@ are loaded from the database::
|
||||||
if not self._state.adding and (
|
if not self._state.adding and (
|
||||||
self.creator_id != self._loaded_values['creator_id']):
|
self.creator_id != self._loaded_values['creator_id']):
|
||||||
raise ValueError("Updating the value of creator isn't allowed")
|
raise ValueError("Updating the value of creator isn't allowed")
|
||||||
super(...).save(*args, **kwargs)
|
super().save(*args, **kwargs)
|
||||||
|
|
||||||
The example above shows a full ``from_db()`` implementation to clarify how that
|
The example above shows a full ``from_db()`` implementation to clarify how that
|
||||||
is done. In this case it would of course be possible to just use ``super()`` call
|
is done. In this case it would of course be possible to just use ``super()`` call
|
||||||
|
@ -184,7 +184,7 @@ all of the instance's fields when a deferred field is reloaded::
|
||||||
if fields.intersection(deferred_fields):
|
if fields.intersection(deferred_fields):
|
||||||
# then load all of them
|
# then load all of them
|
||||||
fields = fields.union(deferred_fields)
|
fields = fields.union(deferred_fields)
|
||||||
super(ExampleModel, self).refresh_from_db(using, fields, **kwargs)
|
super().refresh_from_db(using, fields, **kwargs)
|
||||||
|
|
||||||
.. method:: Model.get_deferred_fields()
|
.. method:: Model.get_deferred_fields()
|
||||||
|
|
||||||
|
|
|
@ -929,7 +929,7 @@ comment model manager to exclude the user group, like this::
|
||||||
|
|
||||||
class BanningCommentManager(CommentManager):
|
class BanningCommentManager(CommentManager):
|
||||||
def get_query_set(self):
|
def get_query_set(self):
|
||||||
qs = super(BanningCommentManager, self).get_query_set()
|
qs = super().get_query_set()
|
||||||
if getattr(settings, 'COMMENTS_BANNED_USERS_GROUP', None):
|
if getattr(settings, 'COMMENTS_BANNED_USERS_GROUP', None):
|
||||||
where = ['user_id NOT IN (SELECT user_id FROM auth_user_groups WHERE group_id = %s)']
|
where = ['user_id NOT IN (SELECT user_id FROM auth_user_groups WHERE group_id = %s)']
|
||||||
params = [settings.COMMENTS_BANNED_USERS_GROUP]
|
params = [settings.COMMENTS_BANNED_USERS_GROUP]
|
||||||
|
|
|
@ -1111,7 +1111,7 @@ code would be required in the app's ``admin.py`` file::
|
||||||
|
|
||||||
def save(self, commit=True):
|
def save(self, commit=True):
|
||||||
# Save the provided password in hashed format
|
# Save the provided password in hashed format
|
||||||
user = super(UserCreationForm, self).save(commit=False)
|
user = super().save(commit=False)
|
||||||
user.set_password(self.cleaned_data["password1"])
|
user.set_password(self.cleaned_data["password1"])
|
||||||
if commit:
|
if commit:
|
||||||
user.save()
|
user.save()
|
||||||
|
|
|
@ -292,7 +292,7 @@ First, we'll add the custom hasher:
|
||||||
algorithm = 'pbkdf2_wrapped_sha1'
|
algorithm = 'pbkdf2_wrapped_sha1'
|
||||||
|
|
||||||
def encode_sha1_hash(self, sha1_hash, salt, iterations=None):
|
def encode_sha1_hash(self, sha1_hash, salt, iterations=None):
|
||||||
return super(PBKDF2WrappedSHA1PasswordHasher, self).encode(sha1_hash, salt, iterations)
|
return super().encode(sha1_hash, salt, iterations)
|
||||||
|
|
||||||
def encode(self, password, salt, iterations=None):
|
def encode(self, password, salt, iterations=None):
|
||||||
_, _, sha1_hash = SHA1PasswordHasher().encode(password, salt).split('$', 2)
|
_, _, sha1_hash = SHA1PasswordHasher().encode(password, salt).split('$', 2)
|
||||||
|
|
|
@ -144,13 +144,13 @@ code snippet shows how you can implement this check::
|
||||||
|
|
||||||
class RangedIntegerField(models.IntegerField):
|
class RangedIntegerField(models.IntegerField):
|
||||||
def __init__(self, min=None, max=None, **kwargs):
|
def __init__(self, min=None, max=None, **kwargs):
|
||||||
super(RangedIntegerField, self).__init__(**kwargs)
|
super().__init__(**kwargs)
|
||||||
self.min = min
|
self.min = min
|
||||||
self.max = max
|
self.max = max
|
||||||
|
|
||||||
def check(self, **kwargs):
|
def check(self, **kwargs):
|
||||||
# Call the superclass
|
# Call the superclass
|
||||||
errors = super(RangedIntegerField, self).check(**kwargs)
|
errors = super().check(**kwargs)
|
||||||
|
|
||||||
# Do some custom checks and add messages to `errors`:
|
# Do some custom checks and add messages to `errors`:
|
||||||
errors.extend(self._check_min_max_values(**kwargs))
|
errors.extend(self._check_min_max_values(**kwargs))
|
||||||
|
@ -182,7 +182,7 @@ the only difference is that the check is a classmethod, not an instance method::
|
||||||
class MyModel(models.Model):
|
class MyModel(models.Model):
|
||||||
@classmethod
|
@classmethod
|
||||||
def check(cls, **kwargs):
|
def check(cls, **kwargs):
|
||||||
errors = super(MyModel, cls).check(**kwargs)
|
errors = super().check(**kwargs)
|
||||||
# ... your own checks ...
|
# ... your own checks ...
|
||||||
return errors
|
return errors
|
||||||
|
|
||||||
|
|
|
@ -218,7 +218,7 @@ template, but you can override it to send more::
|
||||||
|
|
||||||
def get_context_data(self, **kwargs):
|
def get_context_data(self, **kwargs):
|
||||||
# Call the base implementation first to get a context
|
# Call the base implementation first to get a context
|
||||||
context = super(PublisherDetail, self).get_context_data(**kwargs)
|
context = super().get_context_data(**kwargs)
|
||||||
# Add in a QuerySet of all the books
|
# Add in a QuerySet of all the books
|
||||||
context['book_list'] = Book.objects.all()
|
context['book_list'] = Book.objects.all()
|
||||||
return context
|
return context
|
||||||
|
@ -365,7 +365,7 @@ use it in the template::
|
||||||
|
|
||||||
def get_context_data(self, **kwargs):
|
def get_context_data(self, **kwargs):
|
||||||
# Call the base implementation first to get a context
|
# Call the base implementation first to get a context
|
||||||
context = super(PublisherBookList, self).get_context_data(**kwargs)
|
context = super().get_context_data(**kwargs)
|
||||||
# Add in the publisher
|
# Add in the publisher
|
||||||
context['publisher'] = self.publisher
|
context['publisher'] = self.publisher
|
||||||
return context
|
return context
|
||||||
|
@ -419,7 +419,7 @@ object -- so we simply override it and wrap the call::
|
||||||
|
|
||||||
def get_object(self):
|
def get_object(self):
|
||||||
# Call the superclass
|
# Call the superclass
|
||||||
object = super(AuthorDetailView, self).get_object()
|
object = super().get_object()
|
||||||
# Record the last accessed date
|
# Record the last accessed date
|
||||||
object.last_accessed = timezone.now()
|
object.last_accessed = timezone.now()
|
||||||
object.save()
|
object.save()
|
||||||
|
|
|
@ -48,7 +48,7 @@ The view can be constructed using a ``FormView``:
|
||||||
# This method is called when valid form data has been POSTed.
|
# This method is called when valid form data has been POSTed.
|
||||||
# It should return an HttpResponse.
|
# It should return an HttpResponse.
|
||||||
form.send_email()
|
form.send_email()
|
||||||
return super(ContactView, self).form_valid(form)
|
return super().form_valid(form)
|
||||||
|
|
||||||
Notes:
|
Notes:
|
||||||
|
|
||||||
|
@ -215,7 +215,7 @@ to edit, and override
|
||||||
|
|
||||||
def form_valid(self, form):
|
def form_valid(self, form):
|
||||||
form.instance.created_by = self.request.user
|
form.instance.created_by = self.request.user
|
||||||
return super(AuthorCreate, self).form_valid(form)
|
return super().form_valid(form)
|
||||||
|
|
||||||
Note that you'll need to :ref:`decorate this
|
Note that you'll need to :ref:`decorate this
|
||||||
view<decorating-class-based-views>` using
|
view<decorating-class-based-views>` using
|
||||||
|
@ -239,7 +239,7 @@ works for AJAX requests as well as 'normal' form POSTs::
|
||||||
Must be used with an object-based FormView (e.g. CreateView)
|
Must be used with an object-based FormView (e.g. CreateView)
|
||||||
"""
|
"""
|
||||||
def form_invalid(self, form):
|
def form_invalid(self, form):
|
||||||
response = super(AjaxableResponseMixin, self).form_invalid(form)
|
response = super().form_invalid(form)
|
||||||
if self.request.is_ajax():
|
if self.request.is_ajax():
|
||||||
return JsonResponse(form.errors, status=400)
|
return JsonResponse(form.errors, status=400)
|
||||||
else:
|
else:
|
||||||
|
@ -249,7 +249,7 @@ works for AJAX requests as well as 'normal' form POSTs::
|
||||||
# We make sure to call the parent's form_valid() method because
|
# We make sure to call the parent's form_valid() method because
|
||||||
# it might do some processing (in the case of CreateView, it will
|
# it might do some processing (in the case of CreateView, it will
|
||||||
# call form.save() for example).
|
# call form.save() for example).
|
||||||
response = super(AjaxableResponseMixin, self).form_valid(form)
|
response = super().form_valid(form)
|
||||||
if self.request.is_ajax():
|
if self.request.is_ajax():
|
||||||
data = {
|
data = {
|
||||||
'pk': self.object.pk,
|
'pk': self.object.pk,
|
||||||
|
|
|
@ -277,7 +277,7 @@ that it can be used on an instance method. For example::
|
||||||
|
|
||||||
@method_decorator(login_required)
|
@method_decorator(login_required)
|
||||||
def dispatch(self, *args, **kwargs):
|
def dispatch(self, *args, **kwargs):
|
||||||
return super(ProtectedView, self).dispatch(*args, **kwargs)
|
return super().dispatch(*args, **kwargs)
|
||||||
|
|
||||||
Or, more succinctly, you can decorate the class instead and pass the name
|
Or, more succinctly, you can decorate the class instead and pass the name
|
||||||
of the method to be decorated as the keyword argument ``name``::
|
of the method to be decorated as the keyword argument ``name``::
|
||||||
|
|
|
@ -321,10 +321,10 @@ Now we can write a new ``PublisherDetail``::
|
||||||
|
|
||||||
def get(self, request, *args, **kwargs):
|
def get(self, request, *args, **kwargs):
|
||||||
self.object = self.get_object(queryset=Publisher.objects.all())
|
self.object = self.get_object(queryset=Publisher.objects.all())
|
||||||
return super(PublisherDetail, self).get(request, *args, **kwargs)
|
return super().get(request, *args, **kwargs)
|
||||||
|
|
||||||
def get_context_data(self, **kwargs):
|
def get_context_data(self, **kwargs):
|
||||||
context = super(PublisherDetail, self).get_context_data(**kwargs)
|
context = super().get_context_data(**kwargs)
|
||||||
context['publisher'] = self.object
|
context['publisher'] = self.object
|
||||||
return context
|
return context
|
||||||
|
|
||||||
|
@ -461,7 +461,7 @@ Our new ``AuthorDetail`` looks like this::
|
||||||
return reverse('author-detail', kwargs={'pk': self.object.pk})
|
return reverse('author-detail', kwargs={'pk': self.object.pk})
|
||||||
|
|
||||||
def get_context_data(self, **kwargs):
|
def get_context_data(self, **kwargs):
|
||||||
context = super(AuthorDetail, self).get_context_data(**kwargs)
|
context = super().get_context_data(**kwargs)
|
||||||
context['form'] = self.get_form()
|
context['form'] = self.get_form()
|
||||||
return context
|
return context
|
||||||
|
|
||||||
|
@ -478,7 +478,7 @@ Our new ``AuthorDetail`` looks like this::
|
||||||
def form_valid(self, form):
|
def form_valid(self, form):
|
||||||
# Here, we would record the user's interest using the message
|
# Here, we would record the user's interest using the message
|
||||||
# passed in form.cleaned_data['message']
|
# passed in form.cleaned_data['message']
|
||||||
return super(AuthorDetail, self).form_valid(form)
|
return super().form_valid(form)
|
||||||
|
|
||||||
``get_success_url()`` is just providing somewhere to redirect to,
|
``get_success_url()`` is just providing somewhere to redirect to,
|
||||||
which gets used in the default implementation of
|
which gets used in the default implementation of
|
||||||
|
@ -531,7 +531,7 @@ write our own ``get_context_data()`` to make the
|
||||||
model = Author
|
model = Author
|
||||||
|
|
||||||
def get_context_data(self, **kwargs):
|
def get_context_data(self, **kwargs):
|
||||||
context = super(AuthorDisplay, self).get_context_data(**kwargs)
|
context = super().get_context_data(**kwargs)
|
||||||
context['form'] = AuthorInterestForm()
|
context['form'] = AuthorInterestForm()
|
||||||
return context
|
return context
|
||||||
|
|
||||||
|
@ -555,7 +555,7 @@ template as ``AuthorDisplay`` is using on ``GET``::
|
||||||
if not request.user.is_authenticated:
|
if not request.user.is_authenticated:
|
||||||
return HttpResponseForbidden()
|
return HttpResponseForbidden()
|
||||||
self.object = self.get_object()
|
self.object = self.get_object()
|
||||||
return super(AuthorInterest, self).post(request, *args, **kwargs)
|
return super().post(request, *args, **kwargs)
|
||||||
|
|
||||||
def get_success_url(self):
|
def get_success_url(self):
|
||||||
return reverse('author-detail', kwargs={'pk': self.object.pk})
|
return reverse('author-detail', kwargs={'pk': self.object.pk})
|
||||||
|
@ -679,10 +679,9 @@ that the user requested::
|
||||||
if self.request.GET.get('format') == 'json':
|
if self.request.GET.get('format') == 'json':
|
||||||
return self.render_to_json_response(context)
|
return self.render_to_json_response(context)
|
||||||
else:
|
else:
|
||||||
return super(HybridDetailView, self).render_to_response(context)
|
return super().render_to_response(context)
|
||||||
|
|
||||||
Because of the way that Python resolves method overloading, the call to
|
Because of the way that Python resolves method overloading, the call to
|
||||||
``super(HybridDetailView, self).render_to_response(context)`` ends up
|
``super().render_to_response(context)`` ends up calling the
|
||||||
calling the
|
|
||||||
:meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response()`
|
:meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response()`
|
||||||
implementation of :class:`~django.views.generic.base.TemplateResponseMixin`.
|
implementation of :class:`~django.views.generic.base.TemplateResponseMixin`.
|
||||||
|
|
|
@ -121,7 +121,7 @@ all objects, and one that returns only the books by Roald Dahl::
|
||||||
# First, define the Manager subclass.
|
# First, define the Manager subclass.
|
||||||
class DahlBookManager(models.Manager):
|
class DahlBookManager(models.Manager):
|
||||||
def get_queryset(self):
|
def get_queryset(self):
|
||||||
return super(DahlBookManager, self).get_queryset().filter(author='Roald Dahl')
|
return super().get_queryset().filter(author='Roald Dahl')
|
||||||
|
|
||||||
# Then hook it into the Book model explicitly.
|
# Then hook it into the Book model explicitly.
|
||||||
class Book(models.Model):
|
class Book(models.Model):
|
||||||
|
@ -152,11 +152,11 @@ For example::
|
||||||
|
|
||||||
class AuthorManager(models.Manager):
|
class AuthorManager(models.Manager):
|
||||||
def get_queryset(self):
|
def get_queryset(self):
|
||||||
return super(AuthorManager, self).get_queryset().filter(role='A')
|
return super().get_queryset().filter(role='A')
|
||||||
|
|
||||||
class EditorManager(models.Manager):
|
class EditorManager(models.Manager):
|
||||||
def get_queryset(self):
|
def get_queryset(self):
|
||||||
return super(EditorManager, self).get_queryset().filter(role='E')
|
return super().get_queryset().filter(role='E')
|
||||||
|
|
||||||
class Person(models.Model):
|
class Person(models.Model):
|
||||||
first_name = models.CharField(max_length=50)
|
first_name = models.CharField(max_length=50)
|
||||||
|
|
|
@ -804,7 +804,7 @@ to happen whenever you save an object. For example (see
|
||||||
|
|
||||||
def save(self, *args, **kwargs):
|
def save(self, *args, **kwargs):
|
||||||
do_something()
|
do_something()
|
||||||
super(Blog, self).save(*args, **kwargs) # Call the "real" save() method.
|
super().save(*args, **kwargs) # Call the "real" save() method.
|
||||||
do_something_else()
|
do_something_else()
|
||||||
|
|
||||||
You can also prevent saving::
|
You can also prevent saving::
|
||||||
|
@ -819,10 +819,10 @@ You can also prevent saving::
|
||||||
if self.name == "Yoko Ono's blog":
|
if self.name == "Yoko Ono's blog":
|
||||||
return # Yoko shall never have her own blog!
|
return # Yoko shall never have her own blog!
|
||||||
else:
|
else:
|
||||||
super(Blog, self).save(*args, **kwargs) # Call the "real" save() method.
|
super().save(*args, **kwargs) # Call the "real" save() method.
|
||||||
|
|
||||||
It's important to remember to call the superclass method -- that's
|
It's important to remember to call the superclass method -- that's
|
||||||
that ``super(Blog, self).save(*args, **kwargs)`` business -- to ensure
|
that ``super().save(*args, **kwargs)`` business -- to ensure
|
||||||
that the object still gets saved into the database. If you forget to
|
that the object still gets saved into the database. If you forget to
|
||||||
call the superclass method, the default behavior won't happen and the
|
call the superclass method, the default behavior won't happen and the
|
||||||
database won't get touched.
|
database won't get touched.
|
||||||
|
|
|
@ -592,17 +592,17 @@ multiple-database support::
|
||||||
|
|
||||||
def get_queryset(self, request):
|
def get_queryset(self, request):
|
||||||
# Tell Django to look for objects on the 'other' database.
|
# Tell Django to look for objects on the 'other' database.
|
||||||
return super(MultiDBModelAdmin, self).get_queryset(request).using(self.using)
|
return super().get_queryset(request).using(self.using)
|
||||||
|
|
||||||
def formfield_for_foreignkey(self, db_field, request, **kwargs):
|
def formfield_for_foreignkey(self, db_field, request, **kwargs):
|
||||||
# Tell Django to populate ForeignKey widgets using a query
|
# Tell Django to populate ForeignKey widgets using a query
|
||||||
# on the 'other' database.
|
# on the 'other' database.
|
||||||
return super(MultiDBModelAdmin, self).formfield_for_foreignkey(db_field, request, using=self.using, **kwargs)
|
return super().formfield_for_foreignkey(db_field, request, using=self.using, **kwargs)
|
||||||
|
|
||||||
def formfield_for_manytomany(self, db_field, request, **kwargs):
|
def formfield_for_manytomany(self, db_field, request, **kwargs):
|
||||||
# Tell Django to populate ManyToMany widgets using a query
|
# Tell Django to populate ManyToMany widgets using a query
|
||||||
# on the 'other' database.
|
# on the 'other' database.
|
||||||
return super(MultiDBModelAdmin, self).formfield_for_manytomany(db_field, request, using=self.using, **kwargs)
|
return super().formfield_for_manytomany(db_field, request, using=self.using, **kwargs)
|
||||||
|
|
||||||
The implementation provided here implements a multi-database strategy
|
The implementation provided here implements a multi-database strategy
|
||||||
where all objects of a given type are stored on a specific database
|
where all objects of a given type are stored on a specific database
|
||||||
|
@ -618,17 +618,17 @@ similar fashion. They require three customized methods::
|
||||||
|
|
||||||
def get_queryset(self, request):
|
def get_queryset(self, request):
|
||||||
# Tell Django to look for inline objects on the 'other' database.
|
# Tell Django to look for inline objects on the 'other' database.
|
||||||
return super(MultiDBTabularInline, self).get_queryset(request).using(self.using)
|
return super().get_queryset(request).using(self.using)
|
||||||
|
|
||||||
def formfield_for_foreignkey(self, db_field, request, **kwargs):
|
def formfield_for_foreignkey(self, db_field, request, **kwargs):
|
||||||
# Tell Django to populate ForeignKey widgets using a query
|
# Tell Django to populate ForeignKey widgets using a query
|
||||||
# on the 'other' database.
|
# on the 'other' database.
|
||||||
return super(MultiDBTabularInline, self).formfield_for_foreignkey(db_field, request, using=self.using, **kwargs)
|
return super().formfield_for_foreignkey(db_field, request, using=self.using, **kwargs)
|
||||||
|
|
||||||
def formfield_for_manytomany(self, db_field, request, **kwargs):
|
def formfield_for_manytomany(self, db_field, request, **kwargs):
|
||||||
# Tell Django to populate ManyToMany widgets using a query
|
# Tell Django to populate ManyToMany widgets using a query
|
||||||
# on the 'other' database.
|
# on the 'other' database.
|
||||||
return super(MultiDBTabularInline, self).formfield_for_manytomany(db_field, request, using=self.using, **kwargs)
|
return super().formfield_for_manytomany(db_field, request, using=self.using, **kwargs)
|
||||||
|
|
||||||
Once you've written your model admin definitions, they can be
|
Once you've written your model admin definitions, they can be
|
||||||
registered with any ``Admin`` instance::
|
registered with any ``Admin`` instance::
|
||||||
|
|
|
@ -533,7 +533,7 @@ default fields/attributes of the order and deletion fields::
|
||||||
>>> from myapp.forms import ArticleForm
|
>>> from myapp.forms import ArticleForm
|
||||||
>>> class BaseArticleFormSet(BaseFormSet):
|
>>> class BaseArticleFormSet(BaseFormSet):
|
||||||
... def add_fields(self, form, index):
|
... def add_fields(self, form, index):
|
||||||
... super(BaseArticleFormSet, self).add_fields(form, index)
|
... super().add_fields(form, index)
|
||||||
... form.fields["my_field"] = forms.CharField()
|
... form.fields["my_field"] = forms.CharField()
|
||||||
|
|
||||||
>>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet)
|
>>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet)
|
||||||
|
@ -559,7 +559,7 @@ You can pass this parameter when instantiating the formset::
|
||||||
>>> class MyArticleForm(ArticleForm):
|
>>> class MyArticleForm(ArticleForm):
|
||||||
... def __init__(self, *args, **kwargs):
|
... def __init__(self, *args, **kwargs):
|
||||||
... self.user = kwargs.pop('user')
|
... self.user = kwargs.pop('user')
|
||||||
... super(MyArticleForm, self).__init__(*args, **kwargs)
|
... super().__init__(*args, **kwargs)
|
||||||
|
|
||||||
>>> ArticleFormSet = formset_factory(MyArticleForm)
|
>>> ArticleFormSet = formset_factory(MyArticleForm)
|
||||||
>>> formset = ArticleFormSet(form_kwargs={'user': request.user})
|
>>> formset = ArticleFormSet(form_kwargs={'user': request.user})
|
||||||
|
@ -574,7 +574,7 @@ argument - the index of the form in the formset. The index is ``None`` for the
|
||||||
|
|
||||||
>>> class BaseArticleFormSet(BaseFormSet):
|
>>> class BaseArticleFormSet(BaseFormSet):
|
||||||
... def get_form_kwargs(self, index):
|
... def get_form_kwargs(self, index):
|
||||||
... kwargs = super(BaseArticleFormSet, self).get_form_kwargs(index)
|
... kwargs = super().get_form_kwargs(index)
|
||||||
... kwargs['custom_kwarg'] = index
|
... kwargs['custom_kwarg'] = index
|
||||||
... return kwargs
|
... return kwargs
|
||||||
|
|
||||||
|
|
|
@ -797,7 +797,7 @@ Alternatively, you can create a subclass that sets ``self.queryset`` in
|
||||||
|
|
||||||
class BaseAuthorFormSet(BaseModelFormSet):
|
class BaseAuthorFormSet(BaseModelFormSet):
|
||||||
def __init__(self, *args, **kwargs):
|
def __init__(self, *args, **kwargs):
|
||||||
super(BaseAuthorFormSet, self).__init__(*args, **kwargs)
|
super().__init__(*args, **kwargs)
|
||||||
self.queryset = Author.objects.filter(name__startswith='O')
|
self.queryset = Author.objects.filter(name__startswith='O')
|
||||||
|
|
||||||
Then, pass your ``BaseAuthorFormSet`` class to the factory function::
|
Then, pass your ``BaseAuthorFormSet`` class to the factory function::
|
||||||
|
@ -1002,7 +1002,7 @@ class's ``clean`` method::
|
||||||
|
|
||||||
class MyModelFormSet(BaseModelFormSet):
|
class MyModelFormSet(BaseModelFormSet):
|
||||||
def clean(self):
|
def clean(self):
|
||||||
super(MyModelFormSet, self).clean()
|
super().clean()
|
||||||
# example custom validation across forms in the formset
|
# example custom validation across forms in the formset
|
||||||
for form in self.forms:
|
for form in self.forms:
|
||||||
# your custom formset validation
|
# your custom formset validation
|
||||||
|
@ -1018,7 +1018,7 @@ to modify a value in ``ModelFormSet.clean()`` you must modify
|
||||||
|
|
||||||
class MyModelFormSet(BaseModelFormSet):
|
class MyModelFormSet(BaseModelFormSet):
|
||||||
def clean(self):
|
def clean(self):
|
||||||
super(MyModelFormSet, self).clean()
|
super().clean()
|
||||||
|
|
||||||
for form in self.forms:
|
for form in self.forms:
|
||||||
name = form.cleaned_data['name'].upper()
|
name = form.cleaned_data['name'].upper()
|
||||||
|
@ -1164,7 +1164,7 @@ For example, if you want to override ``clean()``::
|
||||||
|
|
||||||
class CustomInlineFormSet(BaseInlineFormSet):
|
class CustomInlineFormSet(BaseInlineFormSet):
|
||||||
def clean(self):
|
def clean(self):
|
||||||
super(CustomInlineFormSet, self).clean()
|
super().clean()
|
||||||
# example custom validation across forms in the formset
|
# example custom validation across forms in the formset
|
||||||
for form in self.forms:
|
for form in self.forms:
|
||||||
# your custom formset validation
|
# your custom formset validation
|
||||||
|
|
|
@ -810,7 +810,7 @@ to query the database for all active sessions for an account)::
|
||||||
return CustomSession
|
return CustomSession
|
||||||
|
|
||||||
def create_model_instance(self, data):
|
def create_model_instance(self, data):
|
||||||
obj = super(SessionStore, self).create_model_instance(data)
|
obj = super().create_model_instance(data)
|
||||||
try:
|
try:
|
||||||
account_id = int(data.get('_auth_user_id'))
|
account_id = int(data.get('_auth_user_id'))
|
||||||
except (ValueError, TypeError):
|
except (ValueError, TypeError):
|
||||||
|
|
|
@ -1735,7 +1735,7 @@ If you need more flexibility, you could also add a new argument to your custom
|
||||||
class Command(makemessages.Command):
|
class Command(makemessages.Command):
|
||||||
|
|
||||||
def add_arguments(self, parser):
|
def add_arguments(self, parser):
|
||||||
super(Command, self).add_arguments(parser)
|
super().add_arguments(parser)
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
'--extra-keyword',
|
'--extra-keyword',
|
||||||
dest='xgettext_keywords',
|
dest='xgettext_keywords',
|
||||||
|
@ -1749,7 +1749,7 @@ If you need more flexibility, you could also add a new argument to your custom
|
||||||
makemessages.Command.xgettext_options[:] +
|
makemessages.Command.xgettext_options[:] +
|
||||||
['--keyword=%s' % kwd for kwd in xgettext_keywords]
|
['--keyword=%s' % kwd for kwd in xgettext_keywords]
|
||||||
)
|
)
|
||||||
super(Command, self).handle(*args, **options)
|
super().handle(*args, **options)
|
||||||
|
|
||||||
Miscellaneous
|
Miscellaneous
|
||||||
=============
|
=============
|
||||||
|
|
|
@ -263,7 +263,7 @@ work::
|
||||||
def default(self, obj):
|
def default(self, obj):
|
||||||
if isinstance(obj, YourCustomType):
|
if isinstance(obj, YourCustomType):
|
||||||
return force_text(obj)
|
return force_text(obj)
|
||||||
return super(LazyEncoder, self).default(obj)
|
return super().default(obj)
|
||||||
|
|
||||||
You can then pass ``cls=LazyEncoder`` to the ``serializers.serialize()``
|
You can then pass ``cls=LazyEncoder`` to the ``serializers.serialize()``
|
||||||
function::
|
function::
|
||||||
|
|
|
@ -479,7 +479,7 @@ fictional ``foobar`` template library::
|
||||||
def __init__(self, params):
|
def __init__(self, params):
|
||||||
params = params.copy()
|
params = params.copy()
|
||||||
options = params.pop('OPTIONS').copy()
|
options = params.pop('OPTIONS').copy()
|
||||||
super(FooBar, self).__init__(params)
|
super().__init__(params)
|
||||||
|
|
||||||
self.engine = foobar.Engine(**options)
|
self.engine = foobar.Engine(**options)
|
||||||
|
|
||||||
|
|
|
@ -704,13 +704,13 @@ If your tests make any database queries, use subclasses
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def setUpClass(cls):
|
def setUpClass(cls):
|
||||||
super(MyTestCase, cls).setUpClass()
|
super().setUpClass()
|
||||||
...
|
...
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def tearDownClass(cls):
|
def tearDownClass(cls):
|
||||||
...
|
...
|
||||||
super(MyTestCase, cls).tearDownClass()
|
super().tearDownClass()
|
||||||
|
|
||||||
Be sure to account for Python's behavior if an exception is raised during
|
Be sure to account for Python's behavior if an exception is raised during
|
||||||
``setUpClass()``. If that happens, neither the tests in the class nor
|
``setUpClass()``. If that happens, neither the tests in the class nor
|
||||||
|
@ -880,14 +880,14 @@ The code for this test may look as follows::
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def setUpClass(cls):
|
def setUpClass(cls):
|
||||||
super(MySeleniumTests, cls).setUpClass()
|
super().setUpClass()
|
||||||
cls.selenium = WebDriver()
|
cls.selenium = WebDriver()
|
||||||
cls.selenium.implicitly_wait(10)
|
cls.selenium.implicitly_wait(10)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def tearDownClass(cls):
|
def tearDownClass(cls):
|
||||||
cls.selenium.quit()
|
cls.selenium.quit()
|
||||||
super(MySeleniumTests, cls).tearDownClass()
|
super().tearDownClass()
|
||||||
|
|
||||||
def test_login(self):
|
def test_login(self):
|
||||||
self.selenium.get('%s%s' % (self.live_server_url, '/login/'))
|
self.selenium.get('%s%s' % (self.live_server_url, '/login/'))
|
||||||
|
|
Loading…
Reference in New Issue