diff options
| author | django-bot <ops@djangoproject.com> | 2022-02-03 20:24:19 +0100 |
|---|---|---|
| committer | Mariusz Felisiak <felisiak.mariusz@gmail.com> | 2022-02-07 20:37:05 +0100 |
| commit | 9c19aff7c7561e3a82978a272ecdaad40dda5c00 (patch) | |
| tree | f0506b668a013d0063e5fba3dbf4863b466713ba /tests/admin_views/admin.py | |
| parent | f68fa8b45dfac545cfc4111d4e52804c86db68d3 (diff) | |
Refs #33476 -- Reformatted code with Black.
Diffstat (limited to 'tests/admin_views/admin.py')
| -rw-r--r-- | tests/admin_views/admin.py | 727 |
1 files changed, 441 insertions, 286 deletions
diff --git a/tests/admin_views/admin.py b/tests/admin_views/admin.py index 9cd078074b..b78746c0ff 100644 --- a/tests/admin_views/admin.py +++ b/tests/admin_views/admin.py @@ -20,33 +20,127 @@ from django.views.decorators.common import no_append_slash from .forms import MediaActionForm from .models import ( - Actor, AdminOrderedAdminMethod, AdminOrderedCallable, AdminOrderedField, - AdminOrderedModelMethod, Album, Answer, Answer2, Article, BarAccount, Book, - Bookmark, Box, Category, Chapter, ChapterXtra1, Child, ChildOfReferer, - Choice, City, Collector, Color, Color2, ComplexSortedPerson, CoverLetter, - CustomArticle, CyclicOne, CyclicTwo, DependentChild, DooHickey, EmptyModel, - EmptyModelHidden, EmptyModelMixin, EmptyModelVisible, ExplicitlyProvidedPK, - ExternalSubscriber, Fabric, FancyDoodad, FieldOverridePost, - FilteredManager, FooAccount, FoodDelivery, FunkyTag, Gadget, Gallery, - GenRelReference, Grommet, ImplicitlyGeneratedPK, Ingredient, - InlineReference, InlineReferer, Inquisition, Language, Link, - MainPrepopulated, ModelWithStringPrimaryKey, NotReferenced, OldSubscriber, - OtherStory, Paper, Parent, ParentWithDependentChildren, ParentWithUUIDPK, - Person, Persona, Picture, Pizza, Plot, PlotDetails, PlotProxy, - PluggableSearchPerson, Podcast, Post, PrePopulatedPost, - PrePopulatedPostLargeSlug, PrePopulatedSubPost, Promo, Question, - ReadablePizza, ReadOnlyPizza, ReadOnlyRelatedField, Recipe, Recommendation, - Recommender, ReferencedByGenRel, ReferencedByInline, ReferencedByParent, - RelatedPrepopulated, RelatedWithUUIDPKModel, Report, Reservation, - Restaurant, RowLevelChangePermissionModel, Section, ShortMessage, Simple, - Sketch, Song, State, Story, StumpJoke, Subscriber, SuperVillain, Telegram, - Thing, Topping, UnchangeableObject, UndeletableObject, UnorderedObject, - UserMessenger, UserProxy, Villain, Vodcast, Whatsit, Widget, Worker, + Actor, + AdminOrderedAdminMethod, + AdminOrderedCallable, + AdminOrderedField, + AdminOrderedModelMethod, + Album, + Answer, + Answer2, + Article, + BarAccount, + Book, + Bookmark, + Box, + Category, + Chapter, + ChapterXtra1, + Child, + ChildOfReferer, + Choice, + City, + Collector, + Color, + Color2, + ComplexSortedPerson, + CoverLetter, + CustomArticle, + CyclicOne, + CyclicTwo, + DependentChild, + DooHickey, + EmptyModel, + EmptyModelHidden, + EmptyModelMixin, + EmptyModelVisible, + ExplicitlyProvidedPK, + ExternalSubscriber, + Fabric, + FancyDoodad, + FieldOverridePost, + FilteredManager, + FooAccount, + FoodDelivery, + FunkyTag, + Gadget, + Gallery, + GenRelReference, + Grommet, + ImplicitlyGeneratedPK, + Ingredient, + InlineReference, + InlineReferer, + Inquisition, + Language, + Link, + MainPrepopulated, + ModelWithStringPrimaryKey, + NotReferenced, + OldSubscriber, + OtherStory, + Paper, + Parent, + ParentWithDependentChildren, + ParentWithUUIDPK, + Person, + Persona, + Picture, + Pizza, + Plot, + PlotDetails, + PlotProxy, + PluggableSearchPerson, + Podcast, + Post, + PrePopulatedPost, + PrePopulatedPostLargeSlug, + PrePopulatedSubPost, + Promo, + Question, + ReadablePizza, + ReadOnlyPizza, + ReadOnlyRelatedField, + Recipe, + Recommendation, + Recommender, + ReferencedByGenRel, + ReferencedByInline, + ReferencedByParent, + RelatedPrepopulated, + RelatedWithUUIDPKModel, + Report, + Reservation, + Restaurant, + RowLevelChangePermissionModel, + Section, + ShortMessage, + Simple, + Sketch, + Song, + State, + Story, + StumpJoke, + Subscriber, + SuperVillain, + Telegram, + Thing, + Topping, + UnchangeableObject, + UndeletableObject, + UnorderedObject, + UserMessenger, + UserProxy, + Villain, + Vodcast, + Whatsit, + Widget, + Worker, WorkHour, ) -@admin.display(ordering='date') +@admin.display(ordering="date") def callable_year(dt_value): try: return dt_value.year @@ -56,19 +150,11 @@ def callable_year(dt_value): class ArticleInline(admin.TabularInline): model = Article - fk_name = 'section' - prepopulated_fields = { - 'title': ('content',) - } + fk_name = "section" + prepopulated_fields = {"title": ("content",)} fieldsets = ( - ('Some fields', { - 'classes': ('collapse',), - 'fields': ('title', 'content') - }), - ('Some other fields', { - 'classes': ('wide',), - 'fields': ('date', 'section') - }) + ("Some fields", {"classes": ("collapse",), "fields": ("title", "content")}), + ("Some other fields", {"classes": ("wide",), "fields": ("date", "section")}), ) @@ -78,13 +164,13 @@ class ChapterInline(admin.TabularInline): class ChapterXtra1Admin(admin.ModelAdmin): list_filter = ( - 'chap', - 'chap__title', - 'chap__book', - 'chap__book__name', - 'chap__book__promo', - 'chap__book__promo__name', - 'guest_author__promo__book', + "chap", + "chap__title", + "chap__book", + "chap__book__name", + "chap__book__promo", + "chap__book__promo__name", + "guest_author__promo__book", ) @@ -92,7 +178,7 @@ class ArticleForm(forms.ModelForm): extra_form_field = forms.BooleanField(required=False) class Meta: - fields = '__all__' + fields = "__all__" model = Article @@ -100,7 +186,11 @@ class ArticleAdminWithExtraUrl(admin.ModelAdmin): def get_urls(self): urlpatterns = super().get_urls() urlpatterns.append( - path('extra.json', self.admin_site.admin_view(self.extra_json), name='article_extra_json') + path( + "extra.json", + self.admin_site.admin_view(self.extra_json), + name="article_extra_json", + ) ) return urlpatterns @@ -110,76 +200,87 @@ class ArticleAdminWithExtraUrl(admin.ModelAdmin): class ArticleAdmin(ArticleAdminWithExtraUrl): list_display = ( - 'content', 'date', callable_year, 'model_year', 'modeladmin_year', - 'model_year_reversed', 'section', lambda obj: obj.title, - 'order_by_expression', 'model_property_year', 'model_month', - 'order_by_f_expression', 'order_by_orderby_expression', + "content", + "date", + callable_year, + "model_year", + "modeladmin_year", + "model_year_reversed", + "section", + lambda obj: obj.title, + "order_by_expression", + "model_property_year", + "model_month", + "order_by_f_expression", + "order_by_orderby_expression", ) - list_editable = ('section',) - list_filter = ('date', 'section') - autocomplete_fields = ('section',) + list_editable = ("section",) + list_filter = ("date", "section") + autocomplete_fields = ("section",) view_on_site = False form = ArticleForm fieldsets = ( - ('Some fields', { - 'classes': ('collapse',), - 'fields': ('title', 'content', 'extra_form_field'), - }), - ('Some other fields', { - 'classes': ('wide',), - 'fields': ('date', 'section', 'sub_section') - }) + ( + "Some fields", + { + "classes": ("collapse",), + "fields": ("title", "content", "extra_form_field"), + }, + ), + ( + "Some other fields", + {"classes": ("wide",), "fields": ("date", "section", "sub_section")}, + ), ) # These orderings aren't particularly useful but show that expressions can # be used for admin_order_field. - @admin.display(ordering=models.F('date') + datetime.timedelta(days=3)) + @admin.display(ordering=models.F("date") + datetime.timedelta(days=3)) def order_by_expression(self, obj): return obj.model_year - @admin.display(ordering=models.F('date')) + @admin.display(ordering=models.F("date")) def order_by_f_expression(self, obj): return obj.model_year - @admin.display(ordering=models.F('date').asc(nulls_last=True)) + @admin.display(ordering=models.F("date").asc(nulls_last=True)) def order_by_orderby_expression(self, obj): return obj.model_year def changelist_view(self, request): - return super().changelist_view(request, extra_context={'extra_var': 'Hello!'}) + return super().changelist_view(request, extra_context={"extra_var": "Hello!"}) - @admin.display(ordering='date', description=None) + @admin.display(ordering="date", description=None) def modeladmin_year(self, obj): return obj.date.year def delete_model(self, request, obj): EmailMessage( - 'Greetings from a deleted object', - 'I hereby inform you that some user deleted me', - 'from@example.com', - ['to@example.com'] + "Greetings from a deleted object", + "I hereby inform you that some user deleted me", + "from@example.com", + ["to@example.com"], ).send() return super().delete_model(request, obj) def save_model(self, request, obj, form, change=True): EmailMessage( - 'Greetings from a created object', - 'I hereby inform you that some user created me', - 'from@example.com', - ['to@example.com'] + "Greetings from a created object", + "I hereby inform you that some user created me", + "from@example.com", + ["to@example.com"], ).send() return super().save_model(request, obj, form, change) class ArticleAdmin2(admin.ModelAdmin): - def has_module_permission(self, request): return False class RowLevelChangePermissionModelAdmin(admin.ModelAdmin): def has_change_permission(self, request, obj=None): - """ Only allow changing objects with even id number """ + """Only allow changing objects with even id number""" return request.user.is_staff and (obj is not None) and (obj.id % 2 == 0) def has_view_permission(self, request, obj=None): @@ -191,63 +292,68 @@ class CustomArticleAdmin(admin.ModelAdmin): """ Tests various hooks for using custom templates and contexts. """ - change_list_template = 'custom_admin/change_list.html' - change_form_template = 'custom_admin/change_form.html' - add_form_template = 'custom_admin/add_form.html' - object_history_template = 'custom_admin/object_history.html' - delete_confirmation_template = 'custom_admin/delete_confirmation.html' - delete_selected_confirmation_template = 'custom_admin/delete_selected_confirmation.html' - popup_response_template = 'custom_admin/popup_response.html' + + change_list_template = "custom_admin/change_list.html" + change_form_template = "custom_admin/change_form.html" + add_form_template = "custom_admin/add_form.html" + object_history_template = "custom_admin/object_history.html" + delete_confirmation_template = "custom_admin/delete_confirmation.html" + delete_selected_confirmation_template = ( + "custom_admin/delete_selected_confirmation.html" + ) + popup_response_template = "custom_admin/popup_response.html" def changelist_view(self, request): - return super().changelist_view(request, extra_context={'extra_var': 'Hello!'}) + return super().changelist_view(request, extra_context={"extra_var": "Hello!"}) class ThingAdmin(admin.ModelAdmin): - list_filter = ('color', 'color__warm', 'color__value', 'pub_date') + list_filter = ("color", "color__warm", "color__value", "pub_date") class InquisitionAdmin(admin.ModelAdmin): - list_display = ('leader', 'country', 'expected', 'sketch') + list_display = ("leader", "country", "expected", "sketch") @admin.display def sketch(self, obj): # A method with the same name as a reverse accessor. - return 'list-display-sketch' + return "list-display-sketch" class SketchAdmin(admin.ModelAdmin): - raw_id_fields = ('inquisition', 'defendant0', 'defendant1') + raw_id_fields = ("inquisition", "defendant0", "defendant1") class FabricAdmin(admin.ModelAdmin): - list_display = ('surface',) - list_filter = ('surface',) + list_display = ("surface",) + list_filter = ("surface",) class BasePersonModelFormSet(BaseModelFormSet): def clean(self): for person_dict in self.cleaned_data: - person = person_dict.get('id') - alive = person_dict.get('alive') + person = person_dict.get("id") + alive = person_dict.get("alive") if person and alive and person.name == "Grace Hopper": raise ValidationError("Grace is not a Zombie") class PersonAdmin(admin.ModelAdmin): - list_display = ('name', 'gender', 'alive') - list_editable = ('gender', 'alive') - list_filter = ('gender',) - search_fields = ('^name',) + list_display = ("name", "gender", "alive") + list_editable = ("gender", "alive") + list_filter = ("gender",) + search_fields = ("^name",) save_as = True def get_changelist_formset(self, request, **kwargs): - return super().get_changelist_formset(request, formset=BasePersonModelFormSet, **kwargs) + return super().get_changelist_formset( + request, formset=BasePersonModelFormSet, **kwargs + ) def get_queryset(self, request): # Order by a field that isn't in list display, to be able to test # whether ordering is preserved. - return super().get_queryset(request).order_by('age') + return super().get_queryset(request).order_by("age") class FooAccountAdmin(admin.StackedInline): @@ -261,14 +367,11 @@ class BarAccountAdmin(admin.StackedInline): class PersonaAdmin(admin.ModelAdmin): - inlines = ( - FooAccountAdmin, - BarAccountAdmin - ) + inlines = (FooAccountAdmin, BarAccountAdmin) class SubscriberAdmin(admin.ModelAdmin): - actions = ['mail_admin'] + actions = ["mail_admin"] action_form = MediaActionForm def delete_queryset(self, request, queryset): @@ -278,38 +381,39 @@ class SubscriberAdmin(admin.ModelAdmin): @admin.action def mail_admin(self, request, selected): EmailMessage( - 'Greetings from a ModelAdmin action', - 'This is the test email from an admin action', - 'from@example.com', - ['to@example.com'] + "Greetings from a ModelAdmin action", + "This is the test email from an admin action", + "from@example.com", + ["to@example.com"], ).send() -@admin.action(description='External mail (Another awesome action)') +@admin.action(description="External mail (Another awesome action)") def external_mail(modeladmin, request, selected): EmailMessage( - 'Greetings from a function action', - 'This is the test email from a function action', - 'from@example.com', - ['to@example.com'] + "Greetings from a function action", + "This is the test email from a function action", + "from@example.com", + ["to@example.com"], ).send() -@admin.action(description='Redirect to (Awesome action)') +@admin.action(description="Redirect to (Awesome action)") def redirect_to(modeladmin, request, selected): from django.http import HttpResponseRedirect - return HttpResponseRedirect('/some-where-else/') + return HttpResponseRedirect("/some-where-else/") -@admin.action(description='Download subscription') + +@admin.action(description="Download subscription") def download(modeladmin, request, selected): - buf = StringIO('This is the content of the file') + buf = StringIO("This is the content of the file") return StreamingHttpResponse(FileWrapper(buf)) -@admin.action(description='No permission to run') +@admin.action(description="No permission to run") def no_perm(modeladmin, request, selected): - return HttpResponse(content='No permission to perform this action', status=403) + return HttpResponse(content="No permission to perform this action", status=403) class ExternalSubscriberAdmin(admin.ModelAdmin): @@ -317,17 +421,17 @@ class ExternalSubscriberAdmin(admin.ModelAdmin): class PodcastAdmin(admin.ModelAdmin): - list_display = ('name', 'release_date') - list_editable = ('release_date',) - date_hierarchy = 'release_date' - ordering = ('name',) + list_display = ("name", "release_date") + list_editable = ("release_date",) + date_hierarchy = "release_date" + ordering = ("name",) class VodcastAdmin(admin.ModelAdmin): - list_display = ('name', 'released') - list_editable = ('released',) + list_display = ("name", "released") + list_editable = ("released",) - ordering = ('name',) + ordering = ("name",) class ChildInline(admin.StackedInline): @@ -338,16 +442,19 @@ class ParentAdmin(admin.ModelAdmin): model = Parent inlines = [ChildInline] save_as = True - list_display = ('id', 'name',) - list_display_links = ('id',) - list_editable = ('name',) + list_display = ( + "id", + "name", + ) + list_display_links = ("id",) + list_editable = ("name",) def save_related(self, request, form, formsets, change): super().save_related(request, form, formsets, change) first_name, last_name = form.instance.name.split() for child in form.instance.child_set.all(): if len(child.name.split()) < 2: - child.name = child.name + ' ' + last_name + child.name = child.name + " " + last_name child.save() @@ -374,13 +481,16 @@ class PictureAdmin(admin.ModelAdmin): class LanguageAdmin(admin.ModelAdmin): - list_display = ['iso', 'shortlist', 'english_name', 'name'] - list_editable = ['shortlist'] + list_display = ["iso", "shortlist", "english_name", "name"] + list_editable = ["shortlist"] class RecommendationAdmin(admin.ModelAdmin): show_full_result_count = False - search_fields = ('=titletranslation__text', '=the_recommender__titletranslation__text',) + search_fields = ( + "=titletranslation__text", + "=the_recommender__titletranslation__text", + ) class WidgetInline(admin.StackedInline): @@ -404,8 +514,8 @@ class FancyDoodadInline(admin.StackedInline): class CategoryAdmin(admin.ModelAdmin): - list_display = ('id', 'collector', 'order') - list_editable = ('order',) + list_display = ("id", "collector", "order") + list_editable = ("order",) class CategoryInline(admin.StackedInline): @@ -414,8 +524,12 @@ class CategoryInline(admin.StackedInline): class CollectorAdmin(admin.ModelAdmin): inlines = [ - WidgetInline, DooHickeyInline, GrommetInline, WhatsitInline, - FancyDoodadInline, CategoryInline + WidgetInline, + DooHickeyInline, + GrommetInline, + WhatsitInline, + FancyDoodadInline, + CategoryInline, ] @@ -433,13 +547,11 @@ class LinkInline(admin.TabularInline): class SubPostInline(admin.TabularInline): model = PrePopulatedSubPost - prepopulated_fields = { - 'subslug': ('subtitle',) - } + prepopulated_fields = {"subslug": ("subtitle",)} def get_readonly_fields(self, request, obj=None): if obj and obj.published: - return ('subslug',) + return ("subslug",) return self.readonly_fields def get_prepopulated_fields(self, request, obj=None): @@ -449,16 +561,14 @@ class SubPostInline(admin.TabularInline): class PrePopulatedPostAdmin(admin.ModelAdmin): - list_display = ['title', 'slug'] - prepopulated_fields = { - 'slug': ('title',) - } + list_display = ["title", "slug"] + prepopulated_fields = {"slug": ("title",)} inlines = [SubPostInline] def get_readonly_fields(self, request, obj=None): if obj and obj.published: - return ('slug',) + return ("slug",) return self.readonly_fields def get_prepopulated_fields(self, request, obj=None): @@ -468,23 +578,26 @@ class PrePopulatedPostAdmin(admin.ModelAdmin): class PrePopulatedPostReadOnlyAdmin(admin.ModelAdmin): - prepopulated_fields = {'slug': ('title',)} + prepopulated_fields = {"slug": ("title",)} def has_change_permission(self, *args, **kwargs): return False class PostAdmin(admin.ModelAdmin): - list_display = ['title', 'public'] + list_display = ["title", "public"] readonly_fields = ( - 'posted', 'awesomeness_level', 'coolness', 'value', - 'multiline', 'multiline_html', lambda obj: "foo", - 'readonly_content', + "posted", + "awesomeness_level", + "coolness", + "value", + "multiline", + "multiline_html", + lambda obj: "foo", + "readonly_content", ) - inlines = [ - LinkInline - ] + inlines = [LinkInline] @admin.display def coolness(self, instance): @@ -493,7 +606,7 @@ class PostAdmin(admin.ModelAdmin): else: return "Unknown coolness." - @admin.display(description='Value in $US') + @admin.display(description="Value in $US") def value(self, instance): return 1000 @@ -511,10 +624,10 @@ class FieldOverridePostForm(forms.ModelForm): class Meta: help_texts = { - 'posted': 'Overridden help text for the date', + "posted": "Overridden help text for the date", } labels = { - 'public': 'Overridden public label', + "public": "Overridden public label", } @@ -524,7 +637,7 @@ class FieldOverridePostAdmin(PostAdmin): class CustomChangeList(ChangeList): def get_queryset(self, request): - return self.root_queryset.order_by('pk').filter(pk=9999) # Doesn't exist + return self.root_queryset.order_by("pk").filter(pk=9999) # Doesn't exist class GadgetAdmin(admin.ModelAdmin): @@ -533,23 +646,23 @@ class GadgetAdmin(admin.ModelAdmin): class ToppingAdmin(admin.ModelAdmin): - readonly_fields = ('pizzas',) + readonly_fields = ("pizzas",) class PizzaAdmin(admin.ModelAdmin): - readonly_fields = ('toppings',) + readonly_fields = ("toppings",) class ReadOnlyRelatedFieldAdmin(admin.ModelAdmin): - readonly_fields = ('chapter', 'language', 'user') + readonly_fields = ("chapter", "language", "user") class StudentAdmin(admin.ModelAdmin): - search_fields = ('name',) + search_fields = ("name",) class ReadOnlyPizzaAdmin(admin.ModelAdmin): - readonly_fields = ('name', 'toppings') + readonly_fields = ("name", "toppings") def has_add_permission(self, request): return False @@ -562,13 +675,13 @@ class ReadOnlyPizzaAdmin(admin.ModelAdmin): class WorkHourAdmin(admin.ModelAdmin): - list_display = ('datum', 'employee') - list_filter = ('employee',) + list_display = ("datum", "employee") + list_filter = ("employee",) class FoodDeliveryAdmin(admin.ModelAdmin): - list_display = ('reference', 'driver', 'restaurant') - list_editable = ('driver', 'restaurant') + list_display = ("reference", "driver", "restaurant") + list_editable = ("driver", "restaurant") class CoverLetterAdmin(admin.ModelAdmin): @@ -580,7 +693,7 @@ class CoverLetterAdmin(admin.ModelAdmin): """ def get_queryset(self, request): - return super().get_queryset(request).defer('date_written') + return super().get_queryset(request).defer("date_written") class PaperAdmin(admin.ModelAdmin): @@ -592,7 +705,7 @@ class PaperAdmin(admin.ModelAdmin): """ def get_queryset(self, request): - return super().get_queryset(request).only('title') + return super().get_queryset(request).only("title") class ShortMessageAdmin(admin.ModelAdmin): @@ -604,7 +717,7 @@ class ShortMessageAdmin(admin.ModelAdmin): """ def get_queryset(self, request): - return super().get_queryset(request).defer('timestamp') + return super().get_queryset(request).defer("timestamp") class TelegramAdmin(admin.ModelAdmin): @@ -616,45 +729,47 @@ class TelegramAdmin(admin.ModelAdmin): """ def get_queryset(self, request): - return super().get_queryset(request).only('title') + return super().get_queryset(request).only("title") class StoryForm(forms.ModelForm): class Meta: - widgets = {'title': forms.HiddenInput} + widgets = {"title": forms.HiddenInput} class StoryAdmin(admin.ModelAdmin): - list_display = ('id', 'title', 'content') - list_display_links = ('title',) # 'id' not in list_display_links - list_editable = ('content',) + list_display = ("id", "title", "content") + list_display_links = ("title",) # 'id' not in list_display_links + list_editable = ("content",) form = StoryForm - ordering = ['-id'] + ordering = ["-id"] class OtherStoryAdmin(admin.ModelAdmin): - list_display = ('id', 'title', 'content') - list_display_links = ('title', 'id') # 'id' in list_display_links - list_editable = ('content',) - ordering = ['-id'] + list_display = ("id", "title", "content") + list_display_links = ("title", "id") # 'id' in list_display_links + list_editable = ("content",) + ordering = ["-id"] class ComplexSortedPersonAdmin(admin.ModelAdmin): - list_display = ('name', 'age', 'is_employee', 'colored_name') - ordering = ('name',) + list_display = ("name", "age", "is_employee", "colored_name") + ordering = ("name",) - @admin.display(ordering='name') + @admin.display(ordering="name") def colored_name(self, obj): return format_html('<span style="color: #ff00ff;">{}</span>', obj.name) class PluggableSearchPersonAdmin(admin.ModelAdmin): - list_display = ('name', 'age') - search_fields = ('name',) + list_display = ("name", "age") + search_fields = ("name",) def get_search_results(self, request, queryset, search_term): queryset, may_have_duplicates = super().get_search_results( - request, queryset, search_term, + request, + queryset, + search_term, ) try: search_term_as_int = int(search_term) @@ -666,51 +781,50 @@ class PluggableSearchPersonAdmin(admin.ModelAdmin): class AlbumAdmin(admin.ModelAdmin): - list_filter = ['title'] + list_filter = ["title"] class QuestionAdmin(admin.ModelAdmin): - ordering = ['-posted'] - search_fields = ['question'] - autocomplete_fields = ['related_questions'] + ordering = ["-posted"] + search_fields = ["question"] + autocomplete_fields = ["related_questions"] class AnswerAdmin(admin.ModelAdmin): - autocomplete_fields = ['question'] + autocomplete_fields = ["question"] class PrePopulatedPostLargeSlugAdmin(admin.ModelAdmin): - prepopulated_fields = { - 'slug': ('title',) - } + prepopulated_fields = {"slug": ("title",)} class AdminOrderedFieldAdmin(admin.ModelAdmin): - ordering = ('order',) - list_display = ('stuff', 'order') + ordering = ("order",) + list_display = ("stuff", "order") class AdminOrderedModelMethodAdmin(admin.ModelAdmin): - ordering = ('order',) - list_display = ('stuff', 'some_order') + ordering = ("order",) + list_display = ("stuff", "some_order") class AdminOrderedAdminMethodAdmin(admin.ModelAdmin): - @admin.display(ordering='order') + @admin.display(ordering="order") def some_admin_order(self, obj): return obj.order - ordering = ('order',) - list_display = ('stuff', 'some_admin_order') + + ordering = ("order",) + list_display = ("stuff", "some_admin_order") -@admin.display(ordering='order') +@admin.display(ordering="order") def admin_ordered_callable(obj): return obj.order class AdminOrderedCallableAdmin(admin.ModelAdmin): - ordering = ('order',) - list_display = ('stuff', admin_ordered_callable) + ordering = ("order",) + list_display = ("stuff", admin_ordered_callable) class ReportAdmin(admin.ModelAdmin): @@ -719,60 +833,67 @@ class ReportAdmin(admin.ModelAdmin): def get_urls(self): # Corner case: Don't call parent implementation - return [path('extra/', self.extra, name='cable_extra')] + return [path("extra/", self.extra, name="cable_extra")] class CustomTemplateBooleanFieldListFilter(BooleanFieldListFilter): - template = 'custom_filter_template.html' + template = "custom_filter_template.html" class CustomTemplateFilterColorAdmin(admin.ModelAdmin): - list_filter = (('warm', CustomTemplateBooleanFieldListFilter),) + list_filter = (("warm", CustomTemplateBooleanFieldListFilter),) # For Selenium Prepopulated tests ------------------------------------- class RelatedPrepopulatedInline1(admin.StackedInline): fieldsets = ( - (None, { - 'fields': ( - ('fk', 'm2m'), - ('pubdate', 'status'), - ('name', 'slug1', 'slug2',), - ), - }), + ( + None, + { + "fields": ( + ("fk", "m2m"), + ("pubdate", "status"), + ( + "name", + "slug1", + "slug2", + ), + ), + }, + ), ) - formfield_overrides = {models.CharField: {'strip': False}} + formfield_overrides = {models.CharField: {"strip": False}} model = RelatedPrepopulated extra = 1 - autocomplete_fields = ['fk', 'm2m'] + autocomplete_fields = ["fk", "m2m"] prepopulated_fields = { - 'slug1': ['name', 'pubdate'], - 'slug2': ['status', 'name'], + "slug1": ["name", "pubdate"], + "slug2": ["status", "name"], } class RelatedPrepopulatedInline2(admin.TabularInline): model = RelatedPrepopulated extra = 1 - autocomplete_fields = ['fk', 'm2m'] + autocomplete_fields = ["fk", "m2m"] prepopulated_fields = { - 'slug1': ['name', 'pubdate'], - 'slug2': ['status', 'name'], + "slug1": ["name", "pubdate"], + "slug2": ["status", "name"], } class RelatedPrepopulatedInline3(admin.TabularInline): model = RelatedPrepopulated extra = 0 - autocomplete_fields = ['fk', 'm2m'] + autocomplete_fields = ["fk", "m2m"] class RelatedPrepopulatedStackedInlineNoFieldsets(admin.StackedInline): model = RelatedPrepopulated extra = 1 prepopulated_fields = { - 'slug1': ['name', 'pubdate'], - 'slug2': ['status'], + "slug1": ["name", "pubdate"], + "slug2": ["status"], } @@ -784,28 +905,29 @@ class MainPrepopulatedAdmin(admin.ModelAdmin): RelatedPrepopulatedStackedInlineNoFieldsets, ] fieldsets = ( - (None, { - 'fields': (('pubdate', 'status'), ('name', 'slug1', 'slug2', 'slug3')) - }), + ( + None, + {"fields": (("pubdate", "status"), ("name", "slug1", "slug2", "slug3"))}, + ), ) - formfield_overrides = {models.CharField: {'strip': False}} + formfield_overrides = {models.CharField: {"strip": False}} prepopulated_fields = { - 'slug1': ['name', 'pubdate'], - 'slug2': ['status', 'name'], - 'slug3': ['name'], + "slug1": ["name", "pubdate"], + "slug2": ["status", "name"], + "slug3": ["name"], } class UnorderedObjectAdmin(admin.ModelAdmin): - list_display = ['id', 'name'] - list_display_links = ['id'] - list_editable = ['name'] + list_display = ["id", "name"] + list_display_links = ["id"] + list_editable = ["name"] list_per_page = 2 class UndeletableObjectAdmin(admin.ModelAdmin): def change_view(self, *args, **kwargs): - kwargs['extra_context'] = {'show_delete': False} + kwargs["extra_context"] = {"show_delete": False} return super().change_view(*args, **kwargs) @@ -831,8 +953,14 @@ class CustomManagerAdmin(admin.ModelAdmin): class MessageTestingAdmin(admin.ModelAdmin): - actions = ["message_debug", "message_info", "message_success", - "message_warning", "message_error", "message_extra_tags"] + actions = [ + "message_debug", + "message_info", + "message_success", + "message_warning", + "message_error", + "message_extra_tags", + ] @admin.action def message_debug(self, request, selected): @@ -860,9 +988,9 @@ class MessageTestingAdmin(admin.ModelAdmin): class ChoiceList(admin.ModelAdmin): - list_display = ['choice'] - readonly_fields = ['choice'] - fields = ['choice'] + list_display = ["choice"] + readonly_fields = ["choice"] + fields = ["choice"] class DependentChildAdminForm(forms.ModelForm): @@ -870,11 +998,16 @@ class DependentChildAdminForm(forms.ModelForm): Issue #20522 Form to test child dependency on parent object's validation """ + def clean(self): - parent = self.cleaned_data.get('parent') - if parent.family_name and parent.family_name != self.cleaned_data.get('family_name'): - raise ValidationError("Children must share a family name with their parents " + - "in this contrived test case") + parent = self.cleaned_data.get("parent") + if parent.family_name and parent.family_name != self.cleaned_data.get( + "family_name" + ): + raise ValidationError( + "Children must share a family name with their parents " + + "in this contrived test case" + ) return super().clean() @@ -889,6 +1022,7 @@ class ParentWithDependentChildrenAdmin(admin.ModelAdmin): # Tests for ticket 11277 ---------------------------------- + class FormWithoutHiddenField(forms.ModelForm): first = forms.CharField() second = forms.CharField() @@ -907,9 +1041,12 @@ class FormWithVisibleAndHiddenField(forms.ModelForm): class EmptyModelVisibleAdmin(admin.ModelAdmin): form = FormWithoutHiddenField fieldsets = ( - (None, { - 'fields': (('first', 'second'),), - }), + ( + None, + { + "fields": (("first", "second"),), + }, + ), ) @@ -933,8 +1070,8 @@ class StateAdminForm(forms.ModelForm): class Meta: model = State - fields = '__all__' - labels = {'name': 'State name (from form’s Meta.labels)'} + fields = "__all__" + labels = {"name": "State name (from form’s Meta.labels)"} @property def changed_data(self): @@ -942,7 +1079,7 @@ class StateAdminForm(forms.ModelForm): if data: # Add arbitrary name to changed_data to test # change message construction. - return data + ['not_a_form_field'] + return data + ["not_a_form_field"] return data @@ -963,20 +1100,20 @@ class CityAdmin(admin.ModelAdmin): def get_formset_kwargs(self, request, obj, inline, prefix): return { **super().get_formset_kwargs(request, obj, inline, prefix), - 'form_kwargs': {'initial': {'name': 'overridden_name'}}, + "form_kwargs": {"initial": {"name": "overridden_name"}}, } class WorkerAdmin(admin.ModelAdmin): def view_on_site(self, obj): - return '/worker/%s/%s/' % (obj.surname, obj.name) + return "/worker/%s/%s/" % (obj.surname, obj.name) class WorkerInlineAdmin(admin.TabularInline): model = Worker def view_on_site(self, obj): - return '/worker_inline/%s/%s/' % (obj.surname, obj.name) + return "/worker_inline/%s/%s/" % (obj.surname, obj.name) class RestaurantAdmin(admin.ModelAdmin): @@ -984,11 +1121,11 @@ class RestaurantAdmin(admin.ModelAdmin): view_on_site = False def get_changeform_initial_data(self, request): - return {'name': 'overridden_value'} + return {"name": "overridden_value"} class FunkyTagAdmin(admin.ModelAdmin): - list_display = ('name', 'content_object') + list_display = ("name", "content_object") class InlineReferenceInline(admin.TabularInline): @@ -1000,11 +1137,11 @@ class InlineRefererAdmin(admin.ModelAdmin): class PlotReadonlyAdmin(admin.ModelAdmin): - readonly_fields = ('plotdetails',) + readonly_fields = ("plotdetails",) class GetFormsetsArgumentCheckingAdmin(admin.ModelAdmin): - fields = ['name'] + fields = ["name"] def add_view(self, request, *args, **kwargs): request.is_add_view = True @@ -1016,19 +1153,26 @@ class GetFormsetsArgumentCheckingAdmin(admin.ModelAdmin): def get_formsets_with_inlines(self, request, obj=None): if request.is_add_view and obj is not None: - raise Exception("'obj' passed to get_formsets_with_inlines wasn't None during add_view") + raise Exception( + "'obj' passed to get_formsets_with_inlines wasn't None during add_view" + ) if not request.is_add_view and obj is None: - raise Exception("'obj' passed to get_formsets_with_inlines was None during change_view") + raise Exception( + "'obj' passed to get_formsets_with_inlines was None during change_view" + ) return super().get_formsets_with_inlines(request, obj) site = admin.AdminSite(name="admin") -site.site_url = '/my-site-url/' +site.site_url = "/my-site-url/" site.register(Article, ArticleAdmin) site.register(CustomArticle, CustomArticleAdmin) site.register( - Section, save_as=True, inlines=[ArticleInline], - readonly_fields=['name_property'], search_fields=['name'], + Section, + save_as=True, + inlines=[ArticleInline], + readonly_fields=["name_property"], + search_fields=["name"], ) site.register(ModelWithStringPrimaryKey) site.register(Color) @@ -1091,7 +1235,7 @@ site.register(InlineReferer, InlineRefererAdmin) site.register(ReferencedByGenRel) site.register(GenRelReference) site.register(ParentWithUUIDPK) -site.register(RelatedPrepopulated, search_fields=['name']) +site.register(RelatedPrepopulated, search_fields=["name"]) site.register(RelatedWithUUIDPKModel) site.register(ReadOnlyRelatedField, ReadOnlyRelatedFieldAdmin) @@ -1113,8 +1257,8 @@ site.register(Topping, ToppingAdmin) site.register(Album, AlbumAdmin) site.register(Song) site.register(Question, QuestionAdmin) -site.register(Answer, AnswerAdmin, date_hierarchy='question__posted') -site.register(Answer2, date_hierarchy='question__expires') +site.register(Answer, AnswerAdmin, date_hierarchy="question__posted") +site.register(Answer2, date_hierarchy="question__expires") site.register(PrePopulatedPost, PrePopulatedPostAdmin) site.register(ComplexSortedPerson, ComplexSortedPersonAdmin) site.register(FilteredManager, CustomManagerAdmin) @@ -1152,9 +1296,9 @@ site2.register(Group, GroupAdmin) site2.register(ParentWithUUIDPK) site2.register( RelatedWithUUIDPKModel, - list_display=['pk', 'parent'], - list_editable=['parent'], - raw_id_fields=['parent'], + list_display=["pk", "parent"], + list_editable=["parent"], + raw_id_fields=["parent"], ) site2.register(Person, save_as_continue=False) site2.register(ReadOnlyRelatedField, ReadOnlyRelatedFieldAdmin) @@ -1166,21 +1310,27 @@ site7.register(Section) site7.register(PrePopulatedPost, PrePopulatedPostReadOnlyAdmin) site7.register( Pizza, - filter_horizontal=['toppings'], + filter_horizontal=["toppings"], fieldsets=( - ('Collapsible', { - 'classes': ['collapse'], - 'fields': ['toppings'], - }), + ( + "Collapsible", + { + "classes": ["collapse"], + "fields": ["toppings"], + }, + ), ), ) site7.register( Question, - filter_horizontal=['related_questions'], + filter_horizontal=["related_questions"], fieldsets=( - ('Not collapsible', { - 'fields': ['related_questions'], - }), + ( + "Not collapsible", + { + "fields": ["related_questions"], + }, + ), ), ) @@ -1188,37 +1338,42 @@ site7.register( # Used to test ModelAdmin.sortable_by and get_sortable_by(). class ArticleAdmin6(admin.ModelAdmin): list_display = ( - 'content', 'date', callable_year, 'model_year', 'modeladmin_year', - 'model_year_reversed', 'section', + "content", + "date", + callable_year, + "model_year", + "modeladmin_year", + "model_year_reversed", + "section", ) - sortable_by = ('date', callable_year) + sortable_by = ("date", callable_year) - @admin.display(ordering='date') + @admin.display(ordering="date") def modeladmin_year(self, obj): return obj.date.year class ActorAdmin6(admin.ModelAdmin): - list_display = ('name', 'age') - sortable_by = ('name',) + list_display = ("name", "age") + sortable_by = ("name",) def get_sortable_by(self, request): - return ('age',) + return ("age",) class ChapterAdmin6(admin.ModelAdmin): - list_display = ('title', 'book') + list_display = ("title", "book") sortable_by = () class ColorAdmin6(admin.ModelAdmin): - list_display = ('value',) + list_display = ("value",) def get_sortable_by(self, request): return () -site6 = admin.AdminSite(name='admin6') +site6 = admin.AdminSite(name="admin6") site6.register(Article, ArticleAdmin6) site6.register(Actor, ActorAdmin6) site6.register(Chapter, ChapterAdmin6) @@ -1240,10 +1395,10 @@ class ActorAdmin9(admin.ModelAdmin): return urls -site9 = admin.AdminSite(name='admin9') +site9 = admin.AdminSite(name="admin9") site9.register(Article, ArticleAdmin9) site9.register(Actor, ActorAdmin9) -site10 = admin.AdminSite(name='admin10') +site10 = admin.AdminSite(name="admin10") site10.final_catch_all_view = False site10.register(Article, ArticleAdminWithExtraUrl) |
