Django提供了非常强大的后台管理功能。其中,每个app的admin.py文件与后台管理是相关的。
首先创建一个新项目:
django-admin.py startproject admin # 创建一个名为admin的项目
cd admin # 进入该项目下
python manage.py startapp blog # 创建名为blog的app
记得将blog加入到settings.py中的INSTALLED_APPS中。
新建一个名为blog的model:
from django.db import models
class Article(models.Model):
title = models.CharField(u'标题', max_length=256)
content = models.TextField(u'内容')
pub_date = models.DateTimeField(u'发表时间', auto_now_add=True, editable=True)
update_time = models.DateTimeField(u'更新时间', auto_now=True, null=True)
同步所有数据表:
python manage.py makemigrations
python manage.py migrate
创建一个超级管理员:
python manage.py createsuperuser
修改admin.py:
from django.http import admin
from .model import Article
admin.site.register(Article)
打开服务器:
python manage.py runserver
修改一下models.py:
class Article(models.Model):
title = models.CharField(u'标题', max_length=256)
content = models.TextField(u'内容')
pub_date = models.DateTimeField(u'发表时间', auto_now_add=True, editable=True)
update_time = models.DateTimeField(u'更新时间', auto_now=True, null=True)
def __str__(self):
return self.title
刷新后台网页,就可以看到:
btw:这里有可能出现中文字符乱码问题,在这里我的原因是数据库编码出错,详细原因可能还需要大家自己百度啦)
from django.contrib import admin
from .models import Article, Person
class ArticleAdmin(admin.ModelAdmin):
list_display = ('title', 'pub_date', 'update_time',)
admin.site.register(Article, ArticleAdmin)
比如想让输入员只看到自己需要的,审核员能看到所有的草稿。这时候需要重写get_queryset函数:
class MyModelAdmin(admin.ModelAdmin):
def get_queryset(self,request):
qs = super(MyModelAdmin,self).get_queryset(request)
if(request.user.is_superuser):
return qs
else:
return qs.filter(author=request.user)
class PersonAdmin(admin.ModelAdmin):
list_display = ('name','age')
search_field = ('name',)
def get_search_results(self,request,queryset,search_term):
queryset, use_distinct = super(PersonAdmin, self).get_search_results(request, queryset, search_term)
try:
search_term_as_int = int(search_term)
queryset |= self.model.objects.filter(age=search_term_as_int)
except:
pass
return queryset, use_distinct
from django.contrib import admin
class ArticleAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change) # obj是修改后的对象,form是返回的表单,当新建对象时change=False;修改对象时change=True
obj.user = request.user
obj.save()
from django.contrib import admin
class ArticleAdmin(admin.ModelAdmin):
def delete_model(self,request,obj):
# 处理 #
obj.delete()
学习资料来源:https://www.dusaiphoto.com/article/detail/2/,此处仅做学习记录。