django (三) admin后台系统

admin后台系统

1. 安装MySQL

1,安装mysql:
    sudo apt install mysql-server
    (安装过程中输入密码并牢记)
    
2,安装后进入mysql:
    mysql -u用户名 -p密码
    mysql -uroot -proot
3,在Django中配置和使用mysql数据库
使用mysql数据库,settings中配置如下:
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'mydb',
            'USER': 'root',
            'PASSWORD': 'root',
            'HOST': '127.0.0.1',
            'PORT': '3306',
        }
    }
4, 添加PyMySQL 
 然后使用pip添加依赖包: pip install PyMySQL
 并在工程目录下的__init__.py中添加以下代码来配置PyMySQL: 
    import pymysql
    pymysql.install_as_MySQLdb()

2. django admin后台系统

Django中默认集成了后台数据管理页面,通过简单的配置就可以实现模型后台的Web控制台。
管理界面通常是给系统管理员使用的,用来完成数据的输入,删除,查询等工作。
使用以下models来示范admin后台系统的用法。
创建一个项目, 用来说明出版社, 书籍和作者的关系。
   假定关系:作者:书籍 => 1:n  (一本书由一个作者完成, 一个作者可以创作多本书)
          出版社:书籍 => n:n (一个出版社可以出版多本书, 一本书可以由多个出版社出版)
要求:
    1. 创建作者author, 出版社publisher,书籍book三个应用.
    2. 给每个应用分别创建首页index.html,且可以在浏览器打开index页面.
    3. 在书籍的index.html中有一个"查看所有书籍"的超链接按钮,点击进入书籍列表list.html页面.
    4. 在书籍list.html中显示所有书名,点击书名可以进入书籍详情detail.html
    5. 在书籍detail.html中可以点击该书的作者和出版社,进入作者的detail.html和出版社的detail.html页面
models.py内容如下:
    # 出版社
    class Publisher(models.Model):
        name = models.CharField(max_length=30)
        address = models.CharField(max_length=100)
        city = models.CharField(max_length=30)
        state_province = models.CharField(max_length=30)
        country = models.CharField(max_length=20)
        website = models.URLField()
        
    # 作者
    class Author(models.Model):
        first_name = models.CharField(max_length=30)
        last_name = models.CharField(max_length=30)
        email = models.EmailField()
        gender = models.BooleanField(default=True)
    # 书籍
    class Book(models.Model):
        title = models.CharField(max_length=100)
        author = models.ForeignKey(Author)
        publishers = models.ManyToManyField(Publisher)
        publish_date = models.DateField()
使用admin后台系统之前,需要先创建一个系统管理员,创建管理员之前需先同步数据库。
    python manager.py createsuperuser
设置为中文
    settingsLANGUAGE_CODE = 'zh-hans'
设置时间,时区
    TIME_ZONE='Asia/Shanghai'
添加自己的数据模型,admin.py中注册: 
    admin.site.register(Publisher)
    admin.site.register(Author)
    admin.site.register(Book)
admin中给model添加数据。
给模型加上__str__函数,比如给Author模型添加str函数,让author的显示更加友好:
    def __str__(self):
        return '%s %s' % (self.first_name, self.last_name)
希望控制admin中添加model数据时的动作,可以修改相应字段的属性。
比如authoremail字段运行添加的时候为空,可以在email字段定义中加上 blank=True(可以空白),
比如bookpublication_date添加 blank=True, null=True(可以为null)属性。
修改models属性之后记得及时做数据迁移。
使用verbose_name属性指定字段的别名:
    比如给publishername字段指定一个中文的别名verbose_name='出版社名称'
    models的修改页面,默认显示的是models定义的str函数返回的字符串。
            

3. 定制admin

通过定义MoldelAdmin来定制modeladmin的表现。比如给Author定义AuthorAdmin
    class AuthorAdmin(admin.ModelAdmin):
        list_display = ('first_name', 'last_name', 'email')
    相应的注册代码也要变化:
    admin.site.register(Author, AuthorAdmin)
Author添加一个搜索框:
    search_fields = ('first_name', 'last_name')
book添加一个过滤器
    list_filter = ('publication_date',)
    过滤器不光可以作用在日期字段上,还可以作用在boolean类型和外键上。
    另一种增加日期过滤的方式:
    date_hierarchy = 'publication_date'
字段排序:
    ordering = ('-publication_date',)
 
修改编辑页面显示的字段及显示顺序,默认按照models中字段的定义顺序显示:
    fields = ('title', 'authors', 'publisher', 'publication_date')
fields相反的字段是exclude
    exclude = ['publication_date',] 
改善多对多关系中对象选择操作,比如给BookAdmin添加如下属性:
    filter_horizontal = ('authors',)
filter_horizontalfilter_vertical 选项只适用于多对多关系。
一对多的外键关系,admin使用select box下拉菜单来表示。如不想用select box,可添加如下属性,让原来一次性加载所有publisherselect box变成填写publisherid
    raw_id_fields = ('publisher',)
让字段分组显示,fieldsets和上面提到的field不能同时出现:
    fieldsets = (
        ('作者', {'fields': ('authors',)}),
        ('出版商', {'fields': ('publisher',)}),
    )
定制list_display字段的显示。比如给Author加一个布尔型gender字段,来表示性别。为了让显示更加人性化:
    # 定制显示属性
    def showgender(self):
        if self.gender:
            return '男'
        else:
            return '女'
    list_display = ('first_name', 'last_name', 'email', showgender)
给该函数设置简短描述,让显示更加友好:
    showgender.short_description = '性别'
可以将modeladmin的属性简单划分为列表页属性和添加、修改页属性
# 列表页属性
list_display,list_filter,search_fields,list_per_page
# 添加、修改页属性
fields ,fieldsets, filter_horizontal, raw_id_fields

转载于:https://www.cnblogs.com/gugubeng/p/9723360.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/279259.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

python博客访问量_史诗级干货-python爬虫之增加CSDN访问量

AI人工智能史诗级干货-python爬虫之增加CSDN访问量史诗级干货-python爬虫之增加CSDN访问量搜索微信公众号:‘AI-ming3526’或者’计算机视觉这件小事’ 获取更多算法、机器学习干货csdn:https://blog.csdn.net/baidu_31657889/github:https://github.com…

弄断过河电缆_你说的是:剪断电缆线

弄断过河电缆Earlier this week we asked you if you’d cut the cable and switched to alternate media sources to get your movie and TV fix. You responded and we’re back with a What You Said roundup. 本周早些时候,我们问您是否要切断电缆并切换到其他媒…

复制粘贴的句子

Today you do things people will not do,tomorrow you will do things people can not do. 你今天做别人不愿做的事,明天就能做别人做不到的事。转载于:https://www.cnblogs.com/wensens/p/9723998.html

路由销毁上一页_路由器原理(数据通信)

路由:对数据包选择路径的过程路由器(也叫网关)智能选择数据传输路由的设备,其端口数量较少!功能:连接网络1.连接异构网络以太网、ATM网络、FDDI网络2.连接远程网络局域网、广域网隔离广播将广播隔离在局域网内路由选择网络安全地址…

您可能没有使用的最佳三星Galaxy功能

Samsung packs its flagship phones with a slew of features—some are even better than stock Android. Either way, there are a lot of things on these phones that you may not be using. Here are some of the best. 包三星旗舰手机用的特性-摆有的甚至比普通的Android…

win7更新错误0x800b0109_win7更新漏洞后产生0x0000006B蓝屏的解决方法图解

这几天不少网友在使用win7更新补丁后就蓝屏了,代码为0x0000006b。发生这一蓝屏问题的都是安装了2016年四月份推出的安全更新补丁,安装后就出现蓝屏,有的网友表示没问题,有的直接蓝了。这个蓝屏重启后依旧,安全模式进不…

获取构造器的信息

获取类构造器的用法与上述获取方法的用法类似,如: import java.lang.reflect.*;public class constructor1 {public constructor1() {}protected constructor1(int i, double d) { } public static void main(String args[]) { try { Class cls Class.f…

如何使用facebook_如果每个人都已经开始使用Facebook,Facebook能否继续发展?

如何使用facebookThere are only so many people on earth, and so many hours in the day. Is that starting to limit the growth of social media? 地球上只有那么多人,一天中有很多小时。 这是否开始限制社交媒体的增长? Think about how much time…

2018-10-03-Python全栈开发-day60-django序列化-part3

联合唯一 clean_字段方法只能对某个字段进行检查,当clean方法执行完之后,最后还会执行clean方法,在clean方法中,可以通过获取数据字典中的值然后进行验证 from django.shortcuts import render,HttpResponsefrom django import fo…

mysql时间字段条件查询_mysql 查询 时间作为查询条件

今天select * from 表名 where to_days(时间字段名) to_days(now());昨天SELECT * FROM 表名 WHERE TO_DAYS( NOW( ) ) - TO_DAYS( 时间字段名) < 1近7天SELECT * FROM 表名 where DATE_SUB(CURDATE(), INTERVAL 7 DAY) < date(时间字段名)近30天SELECT * FROM 表名 whe…

mac按文件名查找文件_如何在Mac上查找和删除大文件

mac按文件名查找文件Freeing up disk space on a full hard drive can be difficult, especially when it’s full of small files. However, there are some excellent tools for macOS that let you find the files taking up the most space and delete the ones you don’t…

Swift5.1 语言参考(十) 语法汇总

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号&#xff1a;山青咏芝&#xff08;shanqingyongzhi&#xff09;➤博客园地址&#xff1a;山青咏芝&#xff08;https://www.cnblogs.com/strengthen/&#xff09;➤GitHub地址&a…

timestamp mysql php_PHP和Mysql的Timestamp互换

在mysql中有三种时间字段类型&#xff1a;DATETIME&#xff0c;DATE和TIMESTAMP。DATETIME以YYYY-MM-DD HH:MM:SS格式的字符串来保存数据&#xff1b;DATE则是只有年月日以YYYY-MM-DD形式的字串&#xff1b;TIMESTAMP类型和PHP中的TIMESTAMP类型名字一样&#xff0c;但是两者基…

dmg是什么文件格式_什么是DMG文件(以及我该如何使用)?

dmg是什么文件格式DMG files are containers for apps in macOS. You open them, drag the app to your Applications folder, and then eject them, saving you the hassle of the dreaded “Install Wizard” of most Windows apps. So if all they are is a folder for an a…

mysql索引三个字段查询两个字段_mysql中关于关联索引的问题——对a,b,c三个字段建立联合索引,那么查询时使用其中的2个作为查询条件,是否还会走索引?...

情况描述&#xff1a;在MySQL的user表中&#xff0c;对a,b,c三个字段建立联合索引&#xff0c;那么查询时使用其中的2个作为查询条件&#xff0c;是否还会走索引&#xff1f;根据查询字段的位置不同来决定&#xff0c;如查询a, a,b a,b,c a,c 都可以走索引的&#…

HDU 3966 Aragorn's Story (树链剖分+线段树)

题意&#xff1a;给你一棵树&#xff0c;然后有三种操作 I L R K: 把L与R的路径上的所有点权值加上K D L R K&#xff1a;把L与R的路径上的所有点权值减去K Q X&#xff1a;查询节点编号为X的权值 思路&#xff1a;树链剖分裸题&#xff08;我还没有怎么学懂&#xff0c;但基本…

canon相机api中文_您应该在佳能相机上掌握的10种相机设置

canon相机api中文Your camera is a tool, and you should be able to use it with total confidence. You should never have to dig through the manual or play around with random buttons trying to work out how to do something on a shoot. Here are the most important…

mysql普通索引自增_mysql中联合索引中的自增列的增长策略

《深入理解MySQL》中一段介绍MyISAM存储引擎中自动增长列的示例,如下1 mysql>create table autoincre_demo2 -> (d1 smallint not nullauto_increment,3 -> d2 smallint not null,4 -> name varchar(10),5 ->index(d2,d1)6 -> )enginemyisam;7 Query OK, 0 r…

spring-boot基础概念与简单应用

1.spring家族 2.应用开发模式 2.1单体式应用 2.2微服务架构 微服务架构中每个服务都可以有自己的数据库 3.微服务架构应当注意的细节 3.1关于"持续集成,持续交付,持续部署" 频繁部署、快速交付以及开发测试流程自动化都将成为未来软件工程的重要组成部分 可行方案(如…

邮箱客户端 gmail支持_如何联系Gmail支持

邮箱客户端 gmail支持Although you may not be able to directly contact Gmail support without subscribing to G Suite for businesses, there are a couple of ways to get the answers you’re looking for online. Let’s look at how you can get help with your Gmail …