Django 07
admin app
admin是django自带的一个非常实用的应用,它负责来管理网站的内容(数据库).admin应用默认已经在INSTALLED_APPS里了, 并且在访问他的url被默认配置为/admin.
INSTALLED_APPS = [
'django.contrib.admin',
# ...
]
urlpatterns = [
url(r'^admin/', admin.site.urls),
# ...
]
首先使用createsuperuser
命令创建管理员用户, 填入用户名, 邮箱, 密码.
$ python manage.py createsuperuser
向admin注册Model, 我们在amdin页面就能看到这个Model了.
# blog/admin.py
from django.contrib import admin
from .models import Blog
admin.site.register(Blog)
我们刚看到admin的默认表单,如需自定义这个界面,我们可以定一个ModelAdmin的子类来描述.
class BookAdmin(admin.ModelAdmin):
pass
admin.site.register(Book, BookAdmin)
也可以使用装饰器的形式.
@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
pass
ModelAdmin 选项
- list_display
class BlogAdmin(admin.ModelAdmin):
list_display = ['id', 'title', 'isHot']
def isHot(self, blog):
return blog.hits >= 1000
isHot.short_description = 'hot'
- list_editable
class BlogAdmin(admin.ModelAdmin):
list_display = ['id', 'title', 'timestamp', 'hits']
list_editable = ['title', 'hits']
- fields
class BlogAdmin(admin.ModelAdmin):
fields = ['title', 'body']
- exclude
class BlogAdmin(admin.ModelAdmin):
exclude = ['hits']
- ordering
class BlogAdmin(admin.ModelAdmin):
ordering = ['-hits']
- search_fields
class BlogAdmin(admin.ModelAdmin):
search_fields = ['title']
- filter_horizontal
- filter_vertical
class ReaderAdmin(admin.ModelAdmin):
filter_horizontal = ['favorite_authors']
- actions
class BlogAdmin(admin.ModelAdmin):
actions = ['clear_hits']
def clear_hits(self, request, queryset):
queryset.update(hits=0)
clear_hits.short_description = "Clear Hits"
- save_model(request, obj, form, change)
- delete_model(request, obj)
class BlogAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
if not change:
obj.hits = random.randint(20, 30)
obj.save()