博客信息

Python Django 模板层(admin后台类)

发布时间:『 2019-08-21 21:56』  博客类别:Python  阅读(973)

本篇博客主要介绍,如何对Django后台管理界面进行定制;

 

首先我们先把默认的Django后台管理界面先弄出来

相关操作

python manage.py startapp changeadmin
python manage.py makemigrations changeadmin
python manage.py migrate
python manage.py createsuperuser


配置模型类

 

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.contrib.auth.models import User
from django.db import models


# Create your models here.
from django.utils import timezone


class BlogArticles(models.Model):
    title = models.CharField(max_length=300)
    # 将Django框架自带的数据库表对应的类User进行关联,related_name是关联查询的关联属性命名
    author = models.ForeignKey(User, related_name='blog_posts')
    body = models.TextField()
    publish = models.DateTimeField(default=timezone.now)

    class Meta:
        # 按照发布时间倒序查询
        ordering = ('-publish',)

    def __unicode__(self):
        return self.title


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.contrib import admin

# Register your models here.
from changeadmin.models import BlogArticles

admin.site.register(BlogArticles)

 

Setting.py中修改

LANGUAGE_CODE = 'zh-Hans'

TIME_ZONE = 'Asia/Shanghai'

 

浏览器登录后界面如下

小李飞刀_Python


小李飞刀_Python


简单的加了四条博客用于待会的测试,adminjavaxl两个用户分别对应了两条博客信息;下面这个是默认的展示效果;

小李飞刀_Python


admin.py修改


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.contrib import admin

# Register your models here.
from changeadmin.models import BlogArticles


class BlogArticlesAdmin(admin.ModelAdmin):
    # 显示表格列表字段
    list_display = ('title', 'author', 'publish',)
    # 条件查询字段
    list_filter = ('publish', 'author',)
    # 搜索框中根据某些字段进行查询
    search_fields = ('title', 'body')
    # 在admin后台类中加入raw_id_fields(只适用于外键)后,会显示外键的详细信息
    raw_id_fields = ("author",)
    # 以某个日期字段分层次查询
    date_hierarchy = 'publish'
    # 排序字段
    ordering = ['publish', 'author']


# admin.site.register(BlogArticles)
admin.site.register(BlogArticles, BlogArticlesAdmin)


小李飞刀_Python



小李飞刀_Python


over......


关键字:     Python       Django       admin.py  

备案号:湘ICP备19000029号

Copyright © 2018-2019 javaxl晓码阁 版权所有