django开发7

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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值