时间:2021-07-01 10:21:17 帮助过:29人阅读
今天给大家介绍django教程(http://www.maiziedu.com/course/python/307-3024/)中的django后台中的一些小技巧,我们都知道在django的后台我们只要加少些代码,就可以实现强大的功能,下面具体介绍下这些小技巧。中文语言支持Django后台的默认语言是英语,可以修改为中文。在settings.py中添加:LANGUAGE_CODE = 'zh-CN'TIME_ZONE = 'Asia/Shanghai'后台使用BootStrapDjango后台的默认样式有些简陋,可以安装并使用Bootstrap1.安装django-admin-bootstrapped:pip3 install django-admin-bootstrapped2.在INSTALLED_APPS(settings.py)中添加:'bootstrap3', #放在admin前面'django_admin_bootstrapped', #放在admin前面'django.contrib.admin',后台列表页自定义样式可以在admin.py中自己设置显示列数、分页、搜索、过滤等功能from django.contrib import adminfrom app.models import Blogclass 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拼接到一块儿显示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.pyclass ArticleAdmin(admin.ModelAdmin): list_display = ('title', 'category', 'self_name')上传图片及显示1.修改models.py使用图片控件ImageFieldimage = models.ImageField(upload_to='images', blank=True)2.修改settings.pySTATIC_ROOT和MEDIA_ROOT需要设置不同路径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.pyurlpatterns = [ 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) |