1、启用站点管理配置如下:

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',  #国际化相关,其必须放在SessionMiddleware之后
    # 'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    # 'django.contrib.messages.middleware.MessageMiddleware',
)

INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
# 'django.contrib.sites',
# 'django.contrib.messages',
# 'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'mysite.books'
)

2、运行 python manage.py syncdb 生成管理界面相关表,第一次运行syncdb时需要创建超级用户,如果在此过程中未创建,则需要显式调用

python manage.py createsuperuser

3、取消注释


# -*-coding:utf-8-*-
from django.conf.urls.defaults import patterns, include, url
from views import hello, current_datetime, render_template, accessDb
from books.views import request_meta, request_meta_2, search_form, search

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
#我们把hello视图函数当作对象处理,而不是调用它,这是python的一个重要特性,函数是一级对象(first-class objects)
url(r'^hello/$',hello),
url(r'^currentdate/$',current_datetime),
url(r'time/\d{1,2}/$',current_datetime),
# 正则表达式利用括号从文本中提取数据,传入到视图函数
url(r'time/(\d{1,2})/$',current_datetime),
url(r'^render/$',render_template),
url(r'^accessDb/$',accessDb),
url(r'^admin/', include(admin.site.urls)),
url(r'^meta1/', request_meta),
url(r'^meta2/', request_meta_2),
url(r'^search_form/', search_form),
url(r'^search/', search),
)
 

4、浏览器访问:http://127.0.0.1:8000/admin/

5. 自定义表单及列表显示 admin.py

# -*-coding:utf-8-*-
from django.contrib import admin
from books.models import Publisher, Author, Book


class AuthorAdmin(admin.ModelAdmin):
    list_display = ('first_name', 'last_name', 'email')
    search_fields = ('first_name', 'last_name')


class BookAdmin(admin.ModelAdmin):
    # 自定义列表相关属性
    list_display = ('title', 'publisher', 'publication_date')
    list_filter = ('publication_date',)
    date_hierarchy = 'publication_date'
    ordering = ('-publication_date',)
    filter_horizontal = ('author',)

    #它是一个包含外键字段名称的元组,它包含的字段将被展现成`` 文本框``
    raw_id_fields = ('publisher',)

    # 自定义表单相关属性
    fields = ('title', 'author', 'publisher', 'publication_date') #可以隐藏某些字段


#这些代码通知管理工具为这些模块逐一提供界面。
admin.site.register(Publisher)
admin.site.register(Author, AuthorAdmin)
admin.site.register(Book, BookAdmin)

备注:当服务启动时,Django从`` url.py`` 引导URLconf,然后执行`` admin.autodiscover()`` 语句。 这个函数遍
历INSTALLED_APPS配置,并且寻找相关的 admin.py文件。 如果在指定的app目录下找到admin.py,它就执行其
中的代码

 

posted on 2016-10-04 11:46  神圣兽国窝窝乡独行侠  阅读(193)  评论(0编辑  收藏  举报