Django后台中的一些小技巧

中文语言支持

Django后台的默认语言是英语,可以修改为中文。在settings.py中添加:

1
2
LANGUAGE_CODE = 'zh-CN'
TIME_ZONE = 'Asia/Shanghai'

后台使用BootStrap

Django后台的默认样式有些简陋,可以安装并使用Bootstrap

1.安装django-admin-bootstrapped:

1
pip3 install django-admin-bootstrapped

2.在INSTALLED_APPS(settings.py)中添加:

1
2
3
'bootstrap3',                  #放在admin前面
'django_admin_bootstrapped', #放在admin前面
'django.contrib.admin',

后台列表页自定义样式

可以在admin.py中自己设置显示列数、分页、搜索、过滤等功能

1
2
3
4
5
6
7
8
9
10
from django.contrib import admin
from app.models import Blog
class BlogAdmin(admin.ModelAdmin):
list_display = ('title', 'content', 'catalog')
list_per_page = 10
search_fields = ['title', ]
list_editable = ['category', ]
list_filter = ['create_time', ]
# Register your models here.
admin.site.register(Blog, BlogAdmin)

自定义列显示

1.修改models.py

比如下面通过self_name将title和content拼接到一块儿显示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Article(models.Model):
title = models.CharField(u'标题', max_length=100)
category = models.CharField(u'分类', max_length=50, blank=True)
content = models.TextField(u'内容', blank=True, null=True)
create_time = models.DateTimeField(u'创建时间', auto_now_add=True)
update_time = models.DateTimeField(u'修改时间', auto_now=True, null=True)

def __str__(self):
return self.title

class Meta:
ordering = ['-create_time']
verbose_name = u'文章'
verbose_name_plural = u'文章管理'

def my_property(self):
return self.title + ":" + self.content

my_property.short_description = "self"

self_name = property(my_property)

2.修改admin.py

1
2
class ArticleAdmin(admin.ModelAdmin):
list_display = ('title', 'category', 'self_name')

上传图片及显示

1.修改models.py

使用图片控件ImageField

1
image = models.ImageField(upload_to='images', blank=True)

2.修改settings.py

STATIC_ROOT和MEDIA_ROOT需要设置不同路径

1
2
3
4
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'article/static')
MEDIA_URL = '/upload/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'article/upload')

3.修改urls.py

1
2
3
4
5
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
......
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
+ static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
八宝粥 wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!