ycliper

Популярное

Музыка Кино и Анимация Автомобили Животные Спорт Путешествия Игры Юмор

Интересные видео

2025 Сериалы Трейлеры Новости Как сделать Видеоуроки Diy своими руками

Топ запросов

смотреть а4 schoolboy runaway турецкий сериал смотреть мультфильмы эдисон
Скачать

Django Tutorial: How To Customize The Admin Interface In Django

Автор: Code master

Загружено: 2016-07-23

Просмотров: 15136

Описание: In this Django tutorial, we are going to learn how to customize the admin interface. Django ships with many of options to improve the Django admin interface. We will take a look at many of them in this tutorial. Let's get started.

How To Customize The Admin Interface In Django
When making changes to the admin interface it's highly recommended that we add a class to our admin file that in encapsolates our options code. We add the class above registering our model and call this class AppnameAdmin so in our case our new class will be called LessonAdmin.

Let's create our class. Create a class in your admin.py file call it LessonAdmin and place it above our lesson admin registration. This class is a subclass that inherits from ModelAdmin class. So, we need to add admin.ModelAdmin to inhertate from the ModelAdmin class.

Code Example
from django.contrib import admin

Register your models here.
from .models import Lesson

class LessonAdmin(admin.ModelAdmin):
#add options here

admin.site.register(Lesson)
Now that we have create the subclass of ModelAdmin we need to hook it into the register of our model. We will place our class name in the register function as an argument. This will allow for our options to be availiable in our admin interface.

Code Example
from django.contrib import admin

Register your models here.
from .models import Lesson

class LessonAdmin(admin.ModelAdmin):
#add options here
pass

admin.site.register(Lesson, LessonAdmin)
Now that we have set up our subclass of ModelAdmin and hooked the subclass into the our register function we can now start too change our display a bit.

Change List Display
Currently our list display only displays the title of our lesson. The list display would be more helpful if it displayed more useful content. For example, maybe if we displayed the slug, publish date and if the lesson was set to draft or plubished status.

Code Example

from django.contrib import admin

Register your models here.
from .models import Lesson

class LessonAdmin(admin.ModelAdmin):
#add options here
list_display = ('title', 'slug','created', 'status')

admin.site.register(Lesson, LessonAdmin)
Admin Interface

list_display Django

Cool now we are able to see some good content in our list view. How about we add some more functionality to our admin interface.

Add List Filter
The filter feature is great for working with time like published and updated in our model or choices like status in our model. It adds a list of filters that we can use to filter through our lessons. We will add a filter for status, created and updated.

The Code

from django.contrib import admin

Register your models here.
from .models import Lesson

class LessonAdmin(admin.ModelAdmin):
#add options here
list_display = ('title', 'slug','created', 'status')
list_filter = ('created', 'updated', 'status')

admin.site.register(Lesson, LessonAdmin)
Admin Interface

filter admin interface django

Search Fields
It would be nice to be able to search our lessons. Django has a feature that will allow us to search through content and display the matching lessons. We will make the title field and body field searchable in our interface.

The Code

from django.contrib import admin

Register your models here.
from .models import Lesson

class LessonAdmin(admin.ModelAdmin):
#add options here
list_display = ('title', 'slug','created', 'status')
list_filter = ('created', 'updated', 'status')
search_fields = ('title', 'body')

admin.site.register(Lesson, LessonAdmin)
The Admin Interface

search fields in Django Admin

Prepopulated Fields
In the previous tutorial I mentioned I would like the slug field to be created on its own so we did not need to do it ourselfes. To this we use prepopulated_fields to populate the field for use. We will prepopulate the slug field from the title field. The prepopulated_fields uses some build in javascript to instancely populate the fields.

The Code

from django.contrib import admin

Register your models here.
from .models import Lesson

class LessonAdmin(admin.ModelAdmin):
#add options here
list_display = ('title', 'slug','created', 'status')
list_filter = ('created', 'updated', 'status')
search_fields = ('title', 'body')
prepopulated_fields = {'slug': ('title', )}

admin.site.register(Lesson, LessonAdmin)
Add a new lesson and when you start to type the title you will notice that the slug field will start to change as well.

Conclusion
For now our admin interface is looking pretty good. We may need to make changes in the future but we are making headway here. If you have any questions about how to customize the admin interface leave a comment below.

Не удается загрузить Youtube-плеер. Проверьте блокировку Youtube в вашей сети.
Повторяем попытку...
Django Tutorial: How To Customize The Admin Interface In Django

Поделиться в:

Доступные форматы для скачивания:

Скачать видео

  • Информация по загрузке:

Скачать аудио

Похожие видео

Python Tutorial: Decorators - Dynamically Alter The Functionality Of Your Functions

Python Tutorial: Decorators - Dynamically Alter The Functionality Of Your Functions

Chillout Lounge - Calm & Relaxing Background Music | Study, Work, Sleep, Meditation, Chill

Chillout Lounge - Calm & Relaxing Background Music | Study, Work, Sleep, Meditation, Chill

Django 2 Building A CMS: How To Create A Local Settings File

Django 2 Building A CMS: How To Create A Local Settings File

Django 2 Building A CMS: How To Configure Our Project For Bootstrap

Django 2 Building A CMS: How To Configure Our Project For Bootstrap

ИСТЕРИКА ВОЕНКОРОВ. Z-ники в ярости из-за приезда Зеленского в Купянск. Требуют отставки Герасимова

ИСТЕРИКА ВОЕНКОРОВ. Z-ники в ярости из-за приезда Зеленского в Купянск. Требуют отставки Герасимова

Linux Command Line for Beginners

Linux Command Line for Beginners

Jazz & Soulful R&B  smooth Grooves  Relaxing instrumental Playlist /Focus/study

Jazz & Soulful R&B smooth Grooves Relaxing instrumental Playlist /Focus/study

Docker за 20 минут

Docker за 20 минут

Custom Analytics // Django Tutorial // Data Collection

Custom Analytics // Django Tutorial // Data Collection

TOP Christmas Songs Playlist 2026 ❄️  Mariah Carey, Ariana Grande, Justin Bieber, Christmas Songs

TOP Christmas Songs Playlist 2026 ❄️ Mariah Carey, Ariana Grande, Justin Bieber, Christmas Songs

Django 2 Building A CMS: Configure Django For Heroku

Django 2 Building A CMS: Configure Django For Heroku

LLM и GPT - как работают большие языковые модели? Визуальное введение в трансформеры

LLM и GPT - как работают большие языковые модели? Визуальное введение в трансформеры

ДНК создал Бог? Самые свежие научные данные о строении. Как работает информация для жизни организмов

ДНК создал Бог? Самые свежие научные данные о строении. Как работает информация для жизни организмов

Модель контекстного протокола (MCP), четко объясненная (почему это важно)

Модель контекстного протокола (MCP), четко объясненная (почему это важно)

TOP Christmas Songs Playlist 2026 ❄️  Mariah Carey, Ariana Grande, Justin Bieber, Christmas Songs

TOP Christmas Songs Playlist 2026 ❄️ Mariah Carey, Ariana Grande, Justin Bieber, Christmas Songs

Что такое Rest API (http)? Soap? GraphQL? Websockets? RPC (gRPC, tRPC). Клиент - сервер. Вся теория

Что такое Rest API (http)? Soap? GraphQL? Websockets? RPC (gRPC, tRPC). Клиент - сервер. Вся теория

AGI Достигнут! ChatGPT 5.2 Рвет ВСЕ Тесты! Внезапно OpenAI Выкатил Новую ИИ! Новая Qwen от Alibaba.

AGI Достигнут! ChatGPT 5.2 Рвет ВСЕ Тесты! Внезапно OpenAI Выкатил Новую ИИ! Новая Qwen от Alibaba.

КАК НЕЛЬЗЯ ХРАНИТЬ ПАРОЛИ (и как нужно) за 11 минут

КАК НЕЛЬЗЯ ХРАНИТЬ ПАРОЛИ (и как нужно) за 11 минут

Операции CRUD веб-API ASP.NET — учебное пособие по .NET8 и Entity Framework Core

Операции CRUD веб-API ASP.NET — учебное пособие по .NET8 и Entity Framework Core

Опасный баг в редакторе кода Google Antigravity — приватные данные под угрозой!

Опасный баг в редакторе кода Google Antigravity — приватные данные под угрозой!

© 2025 ycliper. Все права защищены.



  • Контакты
  • О нас
  • Политика конфиденциальности



Контакты для правообладателей: [email protected]