mirror of https://github.com/django/django.git
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'
|
||||
|
||||
def finish(self):
|
||||
super(DjangoStandaloneHTMLBuilder, self).finish()
|
||||
super().finish()
|
||||
self.info(bold("writing templatebuiltins.js..."))
|
||||
xrefs = self.env.domaindata["std"]["objects"]
|
||||
templatebuiltins = {
|
||||
|
|
|
@ -294,7 +294,7 @@ would override ``get_lookup`` with something like::
|
|||
pass
|
||||
else:
|
||||
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
|
||||
``Lookup`` subclass which handles the relevant value of ``dimension``.
|
||||
|
|
|
@ -274,7 +274,7 @@ the :meth:`~BaseCommand.handle` method must be implemented.
|
|||
|
||||
class Command(BaseCommand):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super(Command, self).__init__(*args, **kwargs)
|
||||
super().__init__(*args, **kwargs)
|
||||
# ...
|
||||
|
||||
.. 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):
|
||||
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
|
||||
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):
|
||||
kwargs['max_length'] = 104
|
||||
super(HandField, self).__init__(*args, **kwargs)
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
def deconstruct(self):
|
||||
name, path, args, kwargs = super(HandField, self).deconstruct()
|
||||
name, path, args, kwargs = super().deconstruct()
|
||||
del kwargs["max_length"]
|
||||
return name, path, args, kwargs
|
||||
|
||||
|
@ -279,10 +279,10 @@ into ``kwargs`` yourself::
|
|||
|
||||
def __init__(self, separator=",", *args, **kwargs):
|
||||
self.separator = separator
|
||||
super(CommaSepField, self).__init__(*args, **kwargs)
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
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
|
||||
if 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):
|
||||
def __init__(self, max_length, *args, **kwargs):
|
||||
self.max_length = max_length
|
||||
super(BetterCharField, self).__init__(*args, **kwargs)
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
def db_type(self, connection):
|
||||
return 'char(%s)' % self.max_length
|
||||
|
@ -576,7 +576,7 @@ For example, Django uses the following method for its
|
|||
:class:`BinaryField`::
|
||||
|
||||
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:
|
||||
return connection.Database.Binary(value)
|
||||
return value
|
||||
|
@ -633,7 +633,7 @@ as::
|
|||
# while letting the caller override them.
|
||||
defaults = {'form_class': MyFormField}
|
||||
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
|
||||
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"
|
||||
|
||||
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]
|
||||
return context
|
||||
|
||||
|
@ -194,7 +194,7 @@ MRO is an acronym for Method Resolution Order.
|
|||
def get_redirect_url(self, *args, **kwargs):
|
||||
article = get_object_or_404(Article, pk=kwargs['pk'])
|
||||
article.update_counter()
|
||||
return super(ArticleCounterRedirectView, self).get_redirect_url(*args, **kwargs)
|
||||
return super().get_redirect_url(*args, **kwargs)
|
||||
|
||||
**Example urls.py**::
|
||||
|
||||
|
|
|
@ -48,7 +48,7 @@ many projects they are typically the most commonly used views.
|
|||
model = Article
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
context = super(ArticleDetailView, self).get_context_data(**kwargs)
|
||||
context = super().get_context_data(**kwargs)
|
||||
context['now'] = timezone.now()
|
||||
return context
|
||||
|
||||
|
@ -117,7 +117,7 @@ many projects they are typically the most commonly used views.
|
|||
model = Article
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
context = super(ArticleListView, self).get_context_data(**kwargs)
|
||||
context = super().get_context_data(**kwargs)
|
||||
context['now'] = timezone.now()
|
||||
return context
|
||||
|
||||
|
|
|
@ -68,7 +68,7 @@ editing content:
|
|||
# This method is called when valid form data has been POSTed.
|
||||
# It should return an HttpResponse.
|
||||
form.send_email()
|
||||
return super(ContactView, self).form_valid(form)
|
||||
return super().form_valid(form)
|
||||
|
||||
**Example myapp/contact.html**:
|
||||
|
||||
|
|
|
@ -15,7 +15,7 @@ Simple mixins
|
|||
arguments provided will make up the returned context. Example usage::
|
||||
|
||||
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)
|
||||
return context
|
||||
|
||||
|
|
|
@ -351,7 +351,7 @@ Conditionally enabling or disabling actions
|
|||
...
|
||||
|
||||
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 'delete_selected' in actions:
|
||||
del actions['delete_selected']
|
||||
|
|
|
@ -910,11 +910,11 @@ subclass::
|
|||
|
||||
def lookups(self, request, model_admin):
|
||||
if request.user.is_superuser:
|
||||
return super(AuthDecadeBornListFilter, self).lookups(request, model_admin)
|
||||
return super().lookups(request, model_admin)
|
||||
|
||||
def queryset(self, request, queryset):
|
||||
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
|
||||
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):
|
||||
def save_model(self, request, obj, form, change):
|
||||
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)
|
||||
|
||||
|
@ -1409,7 +1409,7 @@ templates used by the :class:`ModelAdmin` views:
|
|||
search_fields = ('name',)
|
||||
|
||||
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:
|
||||
search_term_as_int = int(search_term)
|
||||
except ValueError:
|
||||
|
@ -1526,7 +1526,7 @@ templates used by the :class:`ModelAdmin` views:
|
|||
|
||||
class MyModelAdmin(admin.ModelAdmin):
|
||||
def get_urls(self):
|
||||
urls = super(MyModelAdmin, self).get_urls()
|
||||
urls = super().get_urls()
|
||||
my_urls = [
|
||||
url(r'^my_view/$', self.my_view),
|
||||
]
|
||||
|
@ -1578,7 +1578,7 @@ templates used by the :class:`ModelAdmin` views:
|
|||
|
||||
class MyModelAdmin(admin.ModelAdmin):
|
||||
def get_urls(self):
|
||||
urls = super(MyModelAdmin, self).get_urls()
|
||||
urls = super().get_urls()
|
||||
my_urls = [
|
||||
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):
|
||||
if request.user.is_superuser:
|
||||
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
|
||||
directly.
|
||||
|
@ -1648,7 +1648,7 @@ templates used by the :class:`ModelAdmin` views:
|
|||
def formfield_for_foreignkey(self, db_field, request, **kwargs):
|
||||
if db_field.name == "car":
|
||||
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
|
||||
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):
|
||||
if db_field.name == "cars":
|
||||
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)
|
||||
|
||||
|
@ -1685,7 +1685,7 @@ templates used by the :class:`ModelAdmin` views:
|
|||
)
|
||||
if request.user.is_superuser:
|
||||
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
|
||||
|
||||
|
@ -1740,7 +1740,7 @@ templates used by the :class:`ModelAdmin` views:
|
|||
class MyModelAdmin(admin.ModelAdmin):
|
||||
def get_changelist_formset(self, request, **kwargs):
|
||||
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)
|
||||
|
||||
|
@ -1783,7 +1783,7 @@ templates used by the :class:`ModelAdmin` views:
|
|||
|
||||
class MyModelAdmin(admin.ModelAdmin):
|
||||
def get_queryset(self, request):
|
||||
qs = super(MyModelAdmin, self).get_queryset(request)
|
||||
qs = super().get_queryset(request)
|
||||
if request.user.is_superuser:
|
||||
return qs
|
||||
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):
|
||||
extra_context = extra_context or {}
|
||||
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,
|
||||
)
|
||||
|
||||
|
|
|
@ -509,7 +509,7 @@ method::
|
|||
class Entry(models.Model):
|
||||
# ...
|
||||
def save(self, force_insert=False, force_update=False):
|
||||
super(Entry, self).save(force_insert, force_update)
|
||||
super().save(force_insert, force_update)
|
||||
try:
|
||||
ping_google()
|
||||
except Exception:
|
||||
|
|
|
@ -79,7 +79,7 @@ respectively. For example::
|
|||
def __init__(self, *args, **kwargs):
|
||||
kwargs['file_permissions_mode'] = 0o640
|
||||
kwargs['directory_permissions_mode'] = 0o760
|
||||
super(MyStaticFilesStorage, self).__init__(*args, **kwargs)
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
Then set the :setting:`STATICFILES_STORAGE` setting to
|
||||
``'path.to.MyStaticFilesStorage'``.
|
||||
|
|
|
@ -155,7 +155,7 @@ into those elements.
|
|||
return Article.objects.order_by('-pub_date')[:5]
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
context = super(ArticlesFeed, self).get_context_data(**kwargs)
|
||||
context = super().get_context_data(**kwargs)
|
||||
context['foo'] = 'bar'
|
||||
return context
|
||||
|
||||
|
@ -1057,12 +1057,12 @@ For example, you might start implementing an iTunes RSS feed generator like so::
|
|||
|
||||
class iTunesFeed(Rss201rev2Feed):
|
||||
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'
|
||||
return attrs
|
||||
|
||||
def add_root_elements(self, handler):
|
||||
super(iTunesFeed, self).add_root_elements(handler)
|
||||
super().add_root_elements(handler)
|
||||
handler.addQuickElement('itunes:explicit', 'clean')
|
||||
|
||||
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,
|
||||
),
|
||||
)
|
||||
super(PhoneField, self).__init__(
|
||||
super().__init__(
|
||||
error_messages=error_messages, fields=fields,
|
||||
require_all_fields=False, *args, **kwargs
|
||||
)
|
||||
|
@ -1100,7 +1100,7 @@ method::
|
|||
foo_select = forms.ModelMultipleChoiceField(queryset=None)
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super(FooMultipleChoiceForm, self).__init__(*args, **kwargs)
|
||||
super().__init__(*args, **kwargs)
|
||||
self.fields['foo_select'].queryset = ...
|
||||
|
||||
``ModelChoiceField``
|
||||
|
|
|
@ -272,7 +272,7 @@ containing comma-separated email addresses. The full class looks like this::
|
|||
def validate(self, value):
|
||||
"""Check if value consists only of valid emails."""
|
||||
# Use the parent's handling of required fields, etc.
|
||||
super(MultiEmailField, self).validate(value)
|
||||
super().validate(value)
|
||||
for email in value:
|
||||
validate_email(email)
|
||||
|
||||
|
@ -352,7 +352,7 @@ example::
|
|||
...
|
||||
|
||||
def clean(self):
|
||||
cleaned_data = super(ContactForm, self).clean()
|
||||
cleaned_data = super().clean()
|
||||
cc_myself = cleaned_data.get("cc_myself")
|
||||
subject = cleaned_data.get("subject")
|
||||
|
||||
|
@ -367,14 +367,14 @@ example::
|
|||
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.
|
||||
|
||||
The call to ``super(ContactForm, self).clean()`` in the example code ensures
|
||||
that any validation logic in parent classes is maintained. If your form
|
||||
inherits another that doesn't return a ``cleaned_data`` dictionary in its
|
||||
``clean()`` method (doing so is optional), then don't assign ``cleaned_data``
|
||||
to the result of the ``super()`` call and use ``self.cleaned_data`` instead::
|
||||
The call to ``super().clean()`` in the example code ensures that any validation
|
||||
logic in parent classes is maintained. If your form inherits another that
|
||||
doesn't return a ``cleaned_data`` dictionary in its ``clean()`` method (doing
|
||||
so is optional), then don't assign ``cleaned_data`` to the result of the
|
||||
``super()`` call and use ``self.cleaned_data`` instead::
|
||||
|
||||
def clean(self):
|
||||
super(ContactForm, self).clean()
|
||||
super().clean()
|
||||
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):
|
||||
cleaned_data = super(ContactForm, self).clean()
|
||||
cleaned_data = super().clean()
|
||||
cc_myself = cleaned_data.get("cc_myself")
|
||||
subject = cleaned_data.get("subject")
|
||||
|
||||
|
|
|
@ -410,7 +410,7 @@ foundation for custom widgets.
|
|||
widgets.Select(attrs=attrs, choices=months),
|
||||
widgets.Select(attrs=attrs, choices=years),
|
||||
)
|
||||
super(DateSelectorWidget, self).__init__(_widgets, attrs)
|
||||
super().__init__(_widgets, attrs)
|
||||
|
||||
def decompress(self, value):
|
||||
if value:
|
||||
|
|
|
@ -300,7 +300,7 @@ The ``Func`` API is as follows:
|
|||
...
|
||||
|
||||
def as_mysql(self, compiler, connection):
|
||||
return super(ConcatPair, self).as_sql(
|
||||
return super().as_sql(
|
||||
compiler, connection,
|
||||
function='CONCAT_WS',
|
||||
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)'
|
||||
|
||||
def __init__(self, expression, distinct=False, **extra):
|
||||
super(Count, self).__init__(
|
||||
super().__init__(
|
||||
expression,
|
||||
distinct='DISTINCT ' if distinct else '',
|
||||
output_field=IntegerField(),
|
||||
|
@ -776,7 +776,7 @@ an ``__init__()`` method to set some attributes::
|
|||
template = 'COALESCE( %(expressions)s )'
|
||||
|
||||
def __init__(self, expressions, output_field):
|
||||
super(Coalesce, self).__init__(output_field=output_field)
|
||||
super().__init__(output_field=output_field)
|
||||
if len(expressions) < 2:
|
||||
raise ValueError('expressions must have at least 2 elements')
|
||||
for expression in expressions:
|
||||
|
|
|
@ -113,7 +113,7 @@ are loaded from the database::
|
|||
if not self._state.adding and (
|
||||
self.creator_id != self._loaded_values['creator_id']):
|
||||
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
|
||||
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):
|
||||
# then load all of them
|
||||
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()
|
||||
|
||||
|
|
|
@ -929,7 +929,7 @@ comment model manager to exclude the user group, like this::
|
|||
|
||||
class BanningCommentManager(CommentManager):
|
||||
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):
|
||||
where = ['user_id NOT IN (SELECT user_id FROM auth_user_groups WHERE group_id = %s)']
|
||||
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):
|
||||
# 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"])
|
||||
if commit:
|
||||
user.save()
|
||||
|
|
|
@ -292,7 +292,7 @@ First, we'll add the custom hasher:
|
|||
algorithm = 'pbkdf2_wrapped_sha1'
|
||||
|
||||
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):
|
||||
_, _, 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):
|
||||
def __init__(self, min=None, max=None, **kwargs):
|
||||
super(RangedIntegerField, self).__init__(**kwargs)
|
||||
super().__init__(**kwargs)
|
||||
self.min = min
|
||||
self.max = max
|
||||
|
||||
def check(self, **kwargs):
|
||||
# Call the superclass
|
||||
errors = super(RangedIntegerField, self).check(**kwargs)
|
||||
errors = super().check(**kwargs)
|
||||
|
||||
# Do some custom checks and add messages to `errors`:
|
||||
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):
|
||||
@classmethod
|
||||
def check(cls, **kwargs):
|
||||
errors = super(MyModel, cls).check(**kwargs)
|
||||
errors = super().check(**kwargs)
|
||||
# ... your own checks ...
|
||||
return errors
|
||||
|
||||
|
|
|
@ -218,7 +218,7 @@ template, but you can override it to send more::
|
|||
|
||||
def get_context_data(self, **kwargs):
|
||||
# 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
|
||||
context['book_list'] = Book.objects.all()
|
||||
return context
|
||||
|
@ -365,7 +365,7 @@ use it in the template::
|
|||
|
||||
def get_context_data(self, **kwargs):
|
||||
# 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
|
||||
context['publisher'] = self.publisher
|
||||
return context
|
||||
|
@ -419,7 +419,7 @@ object -- so we simply override it and wrap the call::
|
|||
|
||||
def get_object(self):
|
||||
# Call the superclass
|
||||
object = super(AuthorDetailView, self).get_object()
|
||||
object = super().get_object()
|
||||
# Record the last accessed date
|
||||
object.last_accessed = timezone.now()
|
||||
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.
|
||||
# It should return an HttpResponse.
|
||||
form.send_email()
|
||||
return super(ContactView, self).form_valid(form)
|
||||
return super().form_valid(form)
|
||||
|
||||
Notes:
|
||||
|
||||
|
@ -215,7 +215,7 @@ to edit, and override
|
|||
|
||||
def form_valid(self, form):
|
||||
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
|
||||
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)
|
||||
"""
|
||||
def form_invalid(self, form):
|
||||
response = super(AjaxableResponseMixin, self).form_invalid(form)
|
||||
response = super().form_invalid(form)
|
||||
if self.request.is_ajax():
|
||||
return JsonResponse(form.errors, status=400)
|
||||
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
|
||||
# it might do some processing (in the case of CreateView, it will
|
||||
# call form.save() for example).
|
||||
response = super(AjaxableResponseMixin, self).form_valid(form)
|
||||
response = super().form_valid(form)
|
||||
if self.request.is_ajax():
|
||||
data = {
|
||||
'pk': self.object.pk,
|
||||
|
|
|
@ -277,7 +277,7 @@ that it can be used on an instance method. For example::
|
|||
|
||||
@method_decorator(login_required)
|
||||
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
|
||||
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):
|
||||
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):
|
||||
context = super(PublisherDetail, self).get_context_data(**kwargs)
|
||||
context = super().get_context_data(**kwargs)
|
||||
context['publisher'] = self.object
|
||||
return context
|
||||
|
||||
|
@ -461,7 +461,7 @@ Our new ``AuthorDetail`` looks like this::
|
|||
return reverse('author-detail', kwargs={'pk': self.object.pk})
|
||||
|
||||
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()
|
||||
return context
|
||||
|
||||
|
@ -478,7 +478,7 @@ Our new ``AuthorDetail`` looks like this::
|
|||
def form_valid(self, form):
|
||||
# Here, we would record the user's interest using the 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,
|
||||
which gets used in the default implementation of
|
||||
|
@ -531,7 +531,7 @@ write our own ``get_context_data()`` to make the
|
|||
model = Author
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
context = super(AuthorDisplay, self).get_context_data(**kwargs)
|
||||
context = super().get_context_data(**kwargs)
|
||||
context['form'] = AuthorInterestForm()
|
||||
return context
|
||||
|
||||
|
@ -555,7 +555,7 @@ template as ``AuthorDisplay`` is using on ``GET``::
|
|||
if not request.user.is_authenticated:
|
||||
return HttpResponseForbidden()
|
||||
self.object = self.get_object()
|
||||
return super(AuthorInterest, self).post(request, *args, **kwargs)
|
||||
return super().post(request, *args, **kwargs)
|
||||
|
||||
def get_success_url(self):
|
||||
return reverse('author-detail', kwargs={'pk': self.object.pk})
|
||||
|
@ -679,10 +679,9 @@ that the user requested::
|
|||
if self.request.GET.get('format') == 'json':
|
||||
return self.render_to_json_response(context)
|
||||
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
|
||||
``super(HybridDetailView, self).render_to_response(context)`` ends up
|
||||
calling the
|
||||
``super().render_to_response(context)`` ends up calling the
|
||||
:meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response()`
|
||||
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.
|
||||
class DahlBookManager(models.Manager):
|
||||
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.
|
||||
class Book(models.Model):
|
||||
|
@ -152,11 +152,11 @@ For example::
|
|||
|
||||
class AuthorManager(models.Manager):
|
||||
def get_queryset(self):
|
||||
return super(AuthorManager, self).get_queryset().filter(role='A')
|
||||
return super().get_queryset().filter(role='A')
|
||||
|
||||
class EditorManager(models.Manager):
|
||||
def get_queryset(self):
|
||||
return super(EditorManager, self).get_queryset().filter(role='E')
|
||||
return super().get_queryset().filter(role='E')
|
||||
|
||||
class Person(models.Model):
|
||||
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):
|
||||
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()
|
||||
|
||||
You can also prevent saving::
|
||||
|
@ -819,10 +819,10 @@ You can also prevent saving::
|
|||
if self.name == "Yoko Ono's blog":
|
||||
return # Yoko shall never have her own blog!
|
||||
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
|
||||
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
|
||||
call the superclass method, the default behavior won't happen and the
|
||||
database won't get touched.
|
||||
|
|
|
@ -592,17 +592,17 @@ multiple-database support::
|
|||
|
||||
def get_queryset(self, request):
|
||||
# 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):
|
||||
# Tell Django to populate ForeignKey widgets using a query
|
||||
# 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):
|
||||
# Tell Django to populate ManyToMany widgets using a query
|
||||
# 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
|
||||
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):
|
||||
# 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):
|
||||
# Tell Django to populate ForeignKey widgets using a query
|
||||
# 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):
|
||||
# Tell Django to populate ManyToMany widgets using a query
|
||||
# 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
|
||||
registered with any ``Admin`` instance::
|
||||
|
|
|
@ -533,7 +533,7 @@ default fields/attributes of the order and deletion fields::
|
|||
>>> from myapp.forms import ArticleForm
|
||||
>>> class BaseArticleFormSet(BaseFormSet):
|
||||
... def add_fields(self, form, index):
|
||||
... super(BaseArticleFormSet, self).add_fields(form, index)
|
||||
... super().add_fields(form, index)
|
||||
... form.fields["my_field"] = forms.CharField()
|
||||
|
||||
>>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet)
|
||||
|
@ -559,7 +559,7 @@ You can pass this parameter when instantiating the formset::
|
|||
>>> class MyArticleForm(ArticleForm):
|
||||
... def __init__(self, *args, **kwargs):
|
||||
... self.user = kwargs.pop('user')
|
||||
... super(MyArticleForm, self).__init__(*args, **kwargs)
|
||||
... super().__init__(*args, **kwargs)
|
||||
|
||||
>>> ArticleFormSet = formset_factory(MyArticleForm)
|
||||
>>> 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):
|
||||
... def get_form_kwargs(self, index):
|
||||
... kwargs = super(BaseArticleFormSet, self).get_form_kwargs(index)
|
||||
... kwargs = super().get_form_kwargs(index)
|
||||
... kwargs['custom_kwarg'] = index
|
||||
... return kwargs
|
||||
|
||||
|
|
|
@ -797,7 +797,7 @@ Alternatively, you can create a subclass that sets ``self.queryset`` in
|
|||
|
||||
class BaseAuthorFormSet(BaseModelFormSet):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super(BaseAuthorFormSet, self).__init__(*args, **kwargs)
|
||||
super().__init__(*args, **kwargs)
|
||||
self.queryset = Author.objects.filter(name__startswith='O')
|
||||
|
||||
Then, pass your ``BaseAuthorFormSet`` class to the factory function::
|
||||
|
@ -1002,7 +1002,7 @@ class's ``clean`` method::
|
|||
|
||||
class MyModelFormSet(BaseModelFormSet):
|
||||
def clean(self):
|
||||
super(MyModelFormSet, self).clean()
|
||||
super().clean()
|
||||
# example custom validation across forms in the formset
|
||||
for form in self.forms:
|
||||
# your custom formset validation
|
||||
|
@ -1018,7 +1018,7 @@ to modify a value in ``ModelFormSet.clean()`` you must modify
|
|||
|
||||
class MyModelFormSet(BaseModelFormSet):
|
||||
def clean(self):
|
||||
super(MyModelFormSet, self).clean()
|
||||
super().clean()
|
||||
|
||||
for form in self.forms:
|
||||
name = form.cleaned_data['name'].upper()
|
||||
|
@ -1164,7 +1164,7 @@ For example, if you want to override ``clean()``::
|
|||
|
||||
class CustomInlineFormSet(BaseInlineFormSet):
|
||||
def clean(self):
|
||||
super(CustomInlineFormSet, self).clean()
|
||||
super().clean()
|
||||
# example custom validation across forms in the formset
|
||||
for form in self.forms:
|
||||
# your custom formset validation
|
||||
|
|
|
@ -810,7 +810,7 @@ to query the database for all active sessions for an account)::
|
|||
return CustomSession
|
||||
|
||||
def create_model_instance(self, data):
|
||||
obj = super(SessionStore, self).create_model_instance(data)
|
||||
obj = super().create_model_instance(data)
|
||||
try:
|
||||
account_id = int(data.get('_auth_user_id'))
|
||||
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):
|
||||
|
||||
def add_arguments(self, parser):
|
||||
super(Command, self).add_arguments(parser)
|
||||
super().add_arguments(parser)
|
||||
parser.add_argument(
|
||||
'--extra-keyword',
|
||||
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[:] +
|
||||
['--keyword=%s' % kwd for kwd in xgettext_keywords]
|
||||
)
|
||||
super(Command, self).handle(*args, **options)
|
||||
super().handle(*args, **options)
|
||||
|
||||
Miscellaneous
|
||||
=============
|
||||
|
|
|
@ -263,7 +263,7 @@ work::
|
|||
def default(self, obj):
|
||||
if isinstance(obj, YourCustomType):
|
||||
return force_text(obj)
|
||||
return super(LazyEncoder, self).default(obj)
|
||||
return super().default(obj)
|
||||
|
||||
You can then pass ``cls=LazyEncoder`` to the ``serializers.serialize()``
|
||||
function::
|
||||
|
|
|
@ -479,7 +479,7 @@ fictional ``foobar`` template library::
|
|||
def __init__(self, params):
|
||||
params = params.copy()
|
||||
options = params.pop('OPTIONS').copy()
|
||||
super(FooBar, self).__init__(params)
|
||||
super().__init__(params)
|
||||
|
||||
self.engine = foobar.Engine(**options)
|
||||
|
||||
|
|
|
@ -704,13 +704,13 @@ If your tests make any database queries, use subclasses
|
|||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
super(MyTestCase, cls).setUpClass()
|
||||
super().setUpClass()
|
||||
...
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
...
|
||||
super(MyTestCase, cls).tearDownClass()
|
||||
super().tearDownClass()
|
||||
|
||||
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
|
||||
|
@ -880,14 +880,14 @@ The code for this test may look as follows::
|
|||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
super(MySeleniumTests, cls).setUpClass()
|
||||
super().setUpClass()
|
||||
cls.selenium = WebDriver()
|
||||
cls.selenium.implicitly_wait(10)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.selenium.quit()
|
||||
super(MySeleniumTests, cls).tearDownClass()
|
||||
super().tearDownClass()
|
||||
|
||||
def test_login(self):
|
||||
self.selenium.get('%s%s' % (self.live_server_url, '/login/'))
|
||||
|
|
Loading…
Reference in New Issue