41)django-admin
一:介绍
通过django admin可以快速生成后台管理功能。
二:设置
工程同名下settings.py
1)在INSTALLED_APPS中增加django.contrib.admin
2)在INSTALLED_APPS 中增加
django.contrib.auth
django.contrib.contenttypes
django.contrib.messages
django.contrib.sessions
django.contrib.admin依赖上面包
3)在context_processors中
django.contrib.auth.context_processors.auth
django.contrib.messages.context_processors.messages
在MIDDLEWARE,TEMPLATES中增加
django.contrib.auth.middleware.AuthenticationMiddleware
django.contrib.messages.middleware.MessageMiddleware
上面都是默认配置好的
4)在INSTALLED_APPS中增加自己的应用
5)创建ModelAdmin
6)ModelAdmin注册到AdminSite
7)urls.py中配置
from django.contrib import admin
admin.autodiscover()
# And include this URLpattern...
urlpatterns = patterns('',
# ...
(r'^admin/', include(admin.site.urls)),
# ...
)
三:ModelAdmin
ModelAdmin是admin接口,在app下面建立admin.py
示例
方式1:可以定制显示
from django.contrib import admin
from myproject.myapp.models import Author class AuthorAdmin(admin.ModelAdmin):
pass
admin.site.register(Author, AuthorAdmin) 方式2:默认
from django.contrib import admin
from myproject.myapp.models import Author admin.site.register(Author)
四:ModelAdmin常用选项
1)model action
ModelAdmin.
actions
ModelAdmin.
actions_on_top #处理动作在上面显示
ModelAdmin.
actions_on_bottom 处理动作在下面显示#默认(
actions_on_top = True; actions_on_bottom = False
).
ModelAdmin.
actions_selection_counter #动作列表select来显示 默认(
actions_selection_counter = True
)
2)ModelAdmin.
date_hierarchy
处理日期类型DateField
or DateTimeField 添加和修改数据会显示下拉日期
示例:
date_hierarchy = 'pub_date'
date_hierarchy = 'author__pub_date' #author类下的pub_date字段
3)ModelAdmin.
empty_value_display 空值或者None 显示
from django.contrib import admin class AuthorAdmin(admin.ModelAdmin):
empty_value_display = '-empty-' from django.contrib import admin class AuthorAdmin(admin.ModelAdmin):
fields = ('name', 'title', 'view_birth_date') def view_birth_date(self, obj):
return obj.birth_date view_birth_date.empty_value_display = '???'
4)ModelAdmin.
exclude 不显示的字段
class AuthorAdmin(admin.ModelAdmin):
exclude = ('birth_date',)
5)ModelAdmin.
fields 增加或者编辑时显示的字段
class FlatPageAdmin(admin.ModelAdmin):
fields = ('url', 'title', 'content')
6)ModelAdmin.
fieldsets 增加或者编辑页面显示组
from django.contrib import admin class FlatPageAdmin(admin.ModelAdmin):
fieldsets = (
(None, {
'fields': ('url', 'title', 'content', 'sites')
}),
('Advanced options', {
'classes': ('collapse',),
'fields': ('registration_required', 'template_name'),
}),
)
7)ModelAdmin.
filter_horizontal ,
ModelAdmin.
filter_vertical 多对多关系水平多选select
8)ModelAdmin.
list_display 列表数据显示的列
#方式1
class PersonAdmin(admin.ModelAdmin):
list_display = ('first_name', 'last_name') #方式2
class PersonAdmin(admin.ModelAdmin):
list_display = ('upper_case_name',) def upper_case_name(self, obj):
return ("%s %s" % (obj.first_name, obj.last_name)).upper()
upper_case_name.short_description = 'Name' #方式3
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')
备注: 1.ForeignKey显示的__str__中的内容
2 .ManyToManyField
不直接支持,需要自定义方法显示
3. BooleanField
NullBooleanField 会显示on,off代替True,False
4. 显示内容有html,需要在model中实现format_html()
方法
from django.db import models
from django.contrib import admin
from django.utils.html import format_html class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
color_code = models.CharField(max_length=6) def colored_name(self):
return format_html(
'<span style="color: #{};">{} {}</span>',
self.color_code,
self.first_name,
self.last_name,
) class PersonAdmin(admin.ModelAdmin):
list_display = ('first_name', 'last_name', 'colored_name')
9)ModelAdmin.
list_display_links 那些字段点击进入编辑页面(字段必须在list_display中)
class PersonAdmin(admin.ModelAdmin):
list_display = ('first_name', 'last_name', 'birthday')
list_display_links = ('first_name', 'last_name')
10)ModelAdmin.
list_editable 增加或者编辑多行编辑text
11)ModelAdmin.
list_filter 数据列表中的过滤字段,支持
BooleanField
, CharField
, DateField
, DateTimeField
, IntegerField
, ForeignKey
or ManyToManyField
class PersonAdmin(admin.ModelAdmin):
list_filter = ('is_staff', 'company') a class inheriting from django.contrib.admin.SimpleListFilter, which you need to provide the title and parameter_name attributes to and override the lookups and queryset methods, e.g.: from datetime import date from django.contrib import admin
from django.utils.translation import gettext_lazy as _ class DecadeBornListFilter(admin.SimpleListFilter):
# Human-readable title which will be displayed in the
# right admin sidebar just above the filter options.
title = _('decade born') # Parameter for the filter that will be used in the URL query.
parameter_name = 'decade' def lookups(self, request, model_admin):
"""
Returns a list of tuples. The first element in each
tuple is the coded value for the option that will
appear in the URL query. The second element is the
human-readable name for the option that will appear
in the right sidebar.
"""
return (
('80s', _('in the eighties')),
('90s', _('in the nineties')),
) def queryset(self, request, queryset):
"""
Returns the filtered queryset based on the value
provided in the query string and retrievable via
`self.value()`.
"""
# Compare the requested value (either '80s' or '90s')
# to decide how to filter the queryset.
if self.value() == '80s':
return queryset.filter(birthday__gte=date(1980, 1, 1),
birthday__lte=date(1989, 12, 31))
if self.value() == '90s':
return queryset.filter(birthday__gte=date(1990, 1, 1),
birthday__lte=date(1999, 12, 31)) class PersonAdmin(admin.ModelAdmin):
list_filter = (DecadeBornListFilter,)
注:
1.django.contrib.admin.FieldListFilter
2. RelatedOnlyFieldListFilter
a tuple, where the first element is a field name and the second element is a class inheriting from django.contrib.admin.FieldListFilter, for example: class PersonAdmin(admin.ModelAdmin):
list_filter = (
('is_staff', admin.BooleanFieldListFilter),
)
You can limit the choices of a related model to the objects involved in that relation using RelatedOnlyFieldListFilter: class BookAdmin(admin.ModelAdmin):
list_filter = (
('author', admin.RelatedOnlyFieldListFilter),
)
12)ModelAdmin.
list_max_show_all 数据列表,最多显示多少行(总行),默认200行
13)ModelAdmin.
list_per_page 数据列表每页显示多少行
14)ModelAdmin.
list_select_related
class ArticleAdmin(admin.ModelAdmin):
list_select_related = ('author', 'category')
will call select_related('author', 'category'). If you need to specify a dynamic value based on the request, you can implement a get_list_select_related() method.
15)ModelAdmin.
ordering 数据列表,排序字段
16)ModelAdmin.
radio_fields django 默认显示的是choice,可以修改成radio
class PersonAdmin(admin.ModelAdmin):
radio_fields = {"group": admin.VERTICAL}
You have the choice of using HORIZONTAL or VERTICAL from the django.contrib.admin module. Don’t include a field in radio_fields unless it’s a ForeignKey or has choices set.
17) ModelAdmin.
raw_id_fields django默认ForeignKey显示的是select,可以修改成input搜索
class ArticleAdmin(admin.ModelAdmin):
raw_id_fields = ("newspaper",)
18)ModelAdmin.
readonly_fields 不可编辑字段,django默认是可以编辑的
19)ModelAdmin.
search_fields 数据列表 可以搜索的字段
可以是char,text,也可以是foreignkey,manytomany, search_fields = ['foreign_key__related_fieldname']
四:ModelAdmin常用方法
1)ModelAdmin.
save_model
from django.contrib import admin class ArticleAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
obj.user = request.user
super().save_model(request, obj, form, change)
2)ModelAdmin.
delete_model
3)ModelAdmin.
save_formset
class ArticleAdmin(admin.ModelAdmin):
def save_formset(self, request, form, formset, change):
instances = formset.save(commit=False)
for obj in formset.deleted_objects:
obj.delete()
for instance in instances:
instance.user = request.user
instance.save()
formset.save_m2m()
4)ModelAdmin.
get_ordering
(request)
class PersonAdmin(admin.ModelAdmin): def get_ordering(self, request):
if request.user.is_superuser:
return ['name', 'rank']
else:
return ['name']
5)ModelAdmin.
get_search_results
class PersonAdmin(admin.ModelAdmin):
list_display = ('name', 'age')
search_fields = ('name',) def get_search_results(self, request, queryset, search_term):
queryset, use_distinct = super().get_search_results(request, queryset, search_term)
try:
search_term_as_int = int(search_term)
except ValueError:
pass
else:
queryset |= self.model.objects.filter(age=search_term_as_int)
return queryset, use_distinct
五:ModelAdmin可以自定义模板
ModelAdmin.
add_form_template
add_view()
ModelAdmin.
change_form_template
change_view()
ModelAdmin.
change_list_template
changelist_view()
ModelAdmin.
delete_confirmation_template
delete_view()
ModelAdmin.
delete_selected_confirmation_template delete_selected
ModelAdmin.
object_history_template
history_view()
odelAdmin.
popup_response_template
response_add()
, response_change()
, and response_delete()
41)django-admin的更多相关文章
- django admin 设置(转载https://www.cnblogs.com/wumingxiaoyao/p/6928297.html)
Django admin 一些有用的设置 Django自带的后台管理是Django明显特色之一,可以让我们快速便捷管理数据.后台管理可以在各个app的admin.py文件中进行控制.以下是我最近摸 ...
- DJANGO ADMIN 一些有用的设置(转)
DJANGO ADMIN 一些有用的设置 Django自带的后台管理是Django明显特色之一,可以让我们快速便捷管理数据.后台管理可以在各个app的admin.py文件中进行控制.以下是我最近摸 ...
- django admin 使用
Django admin 中一些常用的设置 Django自带的后台管理是Django明显特色之一,可以让我们快速便捷管理数据.后台管理可以在各个app的admin.py文件中进行控制.以下是我最近摸索 ...
- 【Python】解决Django Admin管理界面样式表(CSS Style)丢失问题
配置Django Admin,关于如何启用请参考Django官方文档<Activate the admin site>.但是我在配置过程中登录http://example.com/admi ...
- Django admin操作
无名小妖 昵称:无名小妖园龄:1年6个月粉丝:22关注:1 +加关注 搜索 常用链接 我的随笔 我的评论 我的参与 最新评论 我的标签 我的标签 Python(1) python3 ...
- Django admin美化插件suit应用[原创]
前言 由于比较懒,自己弄了一个用户验证,没有自己写后台,用了django自带的user认证,并通过admin直接进行管理,但默认的admin并不漂亮,于是使用了这个django-suit插件,效果对比 ...
- Django admin 权威指南(一)
版本: Django 1.10 此部分由官方文档<6.5.1 The Django admin site>翻译而来. 6.5.1.1 概览 默认情况下,使用startproject的时候, ...
- Django admin 显示图片
我有一个表用来储存轮播图片,有一个 `picture` 字段储存的是图片的url,图片的 url 通过上传文件到 cdn 获得.目前这个表的编辑是通过自定义一个 `ModelForm`,然后重写 Dj ...
- [系统开发] Django Admin上传图片简单校验
我的 models里有个ImageField字段,用来保存用户头像,希望通过Django Admin上传时校验头像大小,如果太大就报错,并且不保存. 网上有不少方法,有的通过第三方软件实现,有的通过自 ...
- SQLAlchemy连接数据库并在django admin显示
SQLAlchemy 0.7 postgersql 9.0 SQLAlchemy连接数据库有两种方法,一种是classic,一种是modern 1,modern方法 from sqlalch ...
随机推荐
- 二叉树的python可视化和常用操作代码
二叉树是一个重要的数据结构, 本文基于"二叉查找树"的python可视化 pybst 包, 做了一些改造, 可以支持更一般的"二叉树"可视化. 关于二叉树和二叉 ...
- js 对象及空对象或数组及空数组的判断与比较
工作中经常会使用到,这里记录一下 判断是不是对象: let obj = {}; Object.prototype.toString.call(obj) == "[object Object] ...
- 让overflow:auto页面滚动条出现时不跳动
今天看到一篇张鑫旭的文章,转载过来.https://www.zhangxinxu.com/wordpress/2015/01/css-page-scrollbar-toggle-center-no-j ...
- 解决yum安装mysql时Requires: libc.so.6(GLIBC_2.17)(64bit)
1.yum install mysql-community-server 1 2 3 4 5 6 7 Error: Package: mysql-community-libs-5.7.17-1.el7 ...
- GCC编译器原理(二)------编译原理一:目标文件
一.目标文件 在 UNIX® 和 Linux® 中,任何事物都是文件.UNIX 和 Linux 编程实际上是编写处理各种文件的代码.系统由许多类型的文件组成,但目标文件具有一种特殊的设计,提供了灵活和 ...
- luogu 3045 优先队列反悔/bzoj 2590
N头奶牛,价格Pi,K张优惠券,优惠券购买降为Ci,不超过M的钱最多可买多少奶牛 先将c值k小的加入,将它们省下的钱加入优先队列(省下的钱由少到多),在将k+1-n用p排序,再逐个与优先队列中弹出的比 ...
- JS算法练习二
JS算法练习 1.生成4位的随机验证码,可取大小写字母和数字 ? var validateCode = "", /*--存放生成好的验证码字符串--*/ count = 0; /* ...
- 深度优先遍历(DFS)(转)
优先搜索(DFS, Depth First Search)是一个针对图和树的遍历算法.早在19世纪就被用于解决迷宫问题. 对于下面的树而言,DFS方法首先从根节点1开始,其搜索节点顺序是1,2,3,4 ...
- JQuery常见事件
##### 事件 onclick 单机事件 ondblclick 双击事件 onmouseover 鼠标穿过 (子盒子独立) onmouseout 鼠标出去 onmouseenter 鼠标进入 (子盒 ...
- git查看某个文件的提交记录
git log --pretty=oneline 文件路径/文件名 git show 提交id