课程看了很久才发现换了个老师还在讲昨天的内容,浪费时间啊
重新说一遍,按照这个老师的思路,再练习一次吧
一、启用admin:
你用startproject命令创建项目时django admin就默认启用了
For reference, here are the requirements:
- Add 'django.contrib.admin' to your INSTALLED_APPS setting.
- The admin has four dependencies - django.contrib.auth, django.contrib.contenttypes, django.contrib.messages and django.contrib.sessions. If these applications are not in your INSTALLED_APPS list, add them.
- Add django.contrib.auth.context_processors.auth and django.contrib.messages.context_processors.messages to the 'context_processors' option of the DjangoTemplates backend defined in your TEMPLATES as well as django.contrib.auth.middleware.AuthenticationMiddleware and django.contrib.messages.middleware.MessageMiddleware to MIDDLEWARE. These are all active by default, so you only need to do this if you’ve manually tweaked the settings.
- Determine which of your application’s models should be editable in the admin interface.
admin 访问地址
http://localhost:yourport/admin/, by default.
然后是补充的一些内容
fieldsets 分组显示
class ArticleAdmin(admin.ModelAdmin): list_display = ('title','pub_date','account','read_count') date_hierarchy = 'pub_date' fieldsets = (('文章相关',{ 'fields':('title','content'), 'classes': ('wide', 'extrapretty'), }),('高级',{ 'classes':('collapse',), 'fields':(('account','read_count'),'pub_date') }))
上面的classes 是用于设定字段样式,2个默认自带的样式是collapse 和wide
filter_horizontal,filter_vertical 均用于多对多字段
filter_horizontal = ['tags',]
list_display 定义表数据显示哪些列
除了表中有的字段,models自己定义的字段也能放入list_display
from django.db import models from django.contrib import admin class Person(models.Model): name = models.CharField(max_length=50) birthday = models.DateField() def decade_born_in(self): return self.birthday.strftime('%Y')[:3] + "0's" decade_born_in.short_description = 'Birth decade' class PersonAdmin(admin.ModelAdmin): list_display = ('name', 'decade_born_in')
甚至还能玩出花样
from django.utils.html import format_html <br>class Tag(models.Model): """文章标签表""" name = models.CharField(max_length=64,unique=True) date = models.DateTimeField(auto_now_add=True) color_code = models.CharField(max_length=6) def colored_name(self): return format_html( '<span style="color: #{};">{}</span>', self.color_code, self.name, ) def __str__(self): return self.name class TagAdmin(admin.ModelAdmin): list_display = ['name','colored_name']
list_display_links = ('first_name', 'last_name') 点下这2个字段就跳到修改页
list_filter 过滤,把要过滤的字段放到对应列表里就可以
radio_fields 把外键或choice字段由下拉框变成单选框
class ArticleAdmin(admin.ModelAdmin): list_display = ('title','pub_date','account','read_count') date_hierarchy = 'pub_date' filter_horizontal = ['tags',] radio_fields = {'account': admin.VERTICAL}
自动补全
autocomplete_fields = ['account',] 自动补全,外键查询数据多时,方便查找
raw_id_fields 言语无法表示的字段
就把外键变成这样子
readonly_fields = ('address_report',) 只读字段
search_fields 模糊查找
补充的好像就是这些,蛮多的,明天要出差,就拿来好好练习吧。