mirror of
https://github.com/django/django.git
synced 2025-08-04 10:59:45 +00:00
Refs #23919 -- Replaced super(ClassName, self) with super() in docs.
This commit is contained in:
parent
2d96c027f5
commit
dc165ec8e5
36 changed files with 103 additions and 104 deletions
|
@ -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…
Add table
Add a link
Reference in a new issue