第十八 django admin及定制
前情提要
内容:
from django.db import models # Create your models here. class Publisher(models.Model): name = models.CharField(max_length=32) address = models.CharField(max_length=50) city = models.CharField(max_length=60) stat_province = models.CharField(max_length=50) country = models.CharField(max_length=50) websit = models.URLField() def __str__(self): return "<%s>" %(self.name) class Author(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=40) email = models.EmailField() def __str__(self): return "<%s %s>" %(self.first_name,self.last_name) class Book(models.Model): name = models.CharField(max_length=20) authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher) publication_date = models.DateField() def __str__(self): return "<%s>" %(self.name)
一、连接前回,打印书单
1.配置app01/views
2.增加book方法
from fly import models
def book(request):
//post方法返回 if request.method == 'POST': print(request.POST) book_name = request.POST.get('name') publisher_id = request.POST.get('publisher_id') print("==>",request.POST.get('author_ids')) author_ids = request.POST.getlist('author_ids') print(book_name,publisher_id,author_ids)
//如下字段与数据库字段相对应的 new_book = models.Book( name = book_name, publisher_id = publisher_id, publication_date = '2017-07-12' ) new_book.save() new_book.authors.add(*author_ids) //get方法返回如下 books = models.Book.objects.all() publisher_list = models.Publisher.objects.all() author_list = models.Author.objects.all() return render(request,'app01/book.html',{'book':books,'publishers':publisher_list,'authors':author_list}) //返回页面,及参数传递
3.配置/tmplates/app01/book.html
<body> <div>
<!-- 打印书名的列表 --> <ul> {% for i in book %} <li>{{ i.name }}</li> {% endfor %} </ul> <hr/>
<!-- 提交添加书单信息 --> <form method="post" action="">{% csrf_token %} book name:<input type="text" name="name" /> <select name="publisher_id"> {% for publisher in publishers %} <option value="{{ publisher.id }}">{{ publisher.name }}</option> {% endfor %} </select> <select name="author_ids" multiple="multiple"> {% for author in authors %} <option value="{{ author.id }}">{{ author.first_name }}{{ author.last_name }}</option> {% endfor %} </select> <input type="submit" value="创建新书"> </form> </div> </body> </html>
4.配置url
from django.conf.urls import url from app01 import views as fight urlpatterns = [ url(r'suoha/',fight.KanYeMian), url(r'obs/',fight.obsc), url(r'sunzi/',fight.Gs), url(r'form/',fight.book_form), url(r'book/',fight.book) #url(r'(?P<sm>)/',fight.NotOnlyF), #url(r'$',fight.AboutFight), ]
5.查看添加效果
5.1.查看原有书单
5.2.增加新书
5.3.查看结果
5.4.查看数据库
二、配置表单验证及书单添加
1.添加form方法
#!/usr/bin/env python # -*- coding: utf-8 -*- from django import forms class BookForm(forms.Form): name = forms.CharField(max_length=10) #publish_id = forms.IntegerField(widget=forms.Select) publication_date = forms.DateField()
2.添加views方法
from app01 import form from fly import models def book_form(request): Poyan = form.BookForm()
//post请求 if request.method == "POST": Poyan = form.BookForm(request.POST) if Poyan.is_valid(): print("form is ok") print(Poyan.cleaned_data)
//获取form方法,从页面提取的数据,只有两个字段 ‘name’ 和“publication_date” form_data = Poyan.cleaned_data print(request.POST.get('pulisher_id'))
//合成数据,添加“publisher_id” form_data['publisher_id'] = request.POST.get('pulisher_id') print("--"*10) print(form_data)
//将合成数据添加到数据库 book_obj = models.Book(**form_data) book_obj.save() else: print("form is bu ok") //get请求 publisher_list = models.Publisher.objects.all() return render(request,'app01/bookform.html',{'book_form':Poyan,"publishers":publisher_list}) //返回给html及参数
2.配置/tmplates/app01/bookform.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>form haha</title> </head> <body> About form , the future by myself , not anything ! just do it ! <hr/> <form action="" method="post">{% csrf_token %} {{ book_form }} <select name="pulisher_id"> {% for publisher in publishers %} <option value="{{ publisher.id}}">{{ publisher.name }}</option> {% endfor %} </select> <input type="submit" value="添加图书" /> </form> </body> </html>
3.配置book_form的url
from django.conf.urls import url from app01 import views as fight urlpatterns = [ url(r'suoha/',fight.KanYeMian), url(r'obs/',fight.obsc), url(r'sunzi/',fight.Gs), url(r'form/',fight.book_form), url(r'book/',fight.book) #url(r'(?P<sm>)/',fight.NotOnlyF), #url(r'$',fight.AboutFight), ]
4.查看页面及添加数据
4.1.输入不合法数据
4.2.输入合法数据
4.3.查看结果
三、自定义添加书名
1.在form里增加BookModelForm 类
class BookModelForm(forms.ModelForm): class Meta: model = models.Book #包含某些字段 #fields = ('name','publication_date') # 包含所有字段 exclude = () # widgets = { # 'name':forms.TextInput(attrs='class':ckl) # }
2.配置views
def book_modelform(request): Boyan = form.BookModelForm if request.method == "POST": print(request.POST)
//直接获取POST输入 Boyan = form.BookModelForm(request.POST) if Boyan.is_valid(): print("form is ok")
//直接存入到数据库 Boyan.save() return render(request,'app01/bookmodelform.html',{'model_from':Boyan})
3.配置html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> . ckl { background-color: #0cfff2; } </style> </head> <body> <form action="" method="post">{% csrf_token %} {{ model_from }} <input type="submit" value="添加图书" /> </form> </body> </body> </html>
4.配置urls
from django.conf.urls import url from app01 import views as fight urlpatterns = [ url(r'suoha/',fight.KanYeMian), url(r'obs/',fight.obsc), url(r'sunzi/',fight.Gs), url(r'form/',fight.book_form), url(r'book/',fight.book), url(r'model/',fight.book_modelform) #url(r'(?P<sm>)/',fight.NotOnlyF), #url(r'$',fight.AboutFight), ]
5.访问页面
查看结果:
四、django admin自定义
1.原始页面同上面,只有一项
2.新增出版社及出版日期
from django.contrib import admin # Register your models here. from fly import models class BookAdmin(admin.ModelAdmin): list_display = ('name','publisher','publication_date') admin.site.register(models.Publisher) admin.site.register(models.Author) admin.site.register(models.Book,BookAdmin)
2.1.查看页面
3.添加搜索框
3.1.修改admin
内容:
from django.contrib import admin # Register your models here. from fly import models class BookAdmin(admin.ModelAdmin): list_display = ('name','publisher','publication_date')
//增加搜索 search_fields = ('name','publisher__name') //外键关联必须要两个下划线 admin.site.register(models.Publisher) admin.site.register(models.Author) admin.site.register(models.Book,BookAdmin)
3.2.查看结果
搜索出版商:
搜索书名:
4.添加右侧过滤器
4.1.修改admin
from django.contrib import admin # Register your models here. from fly import models class BookAdmin(admin.ModelAdmin): list_display = ('name','publisher','publication_date') search_fields = ('name','publisher__name') list_filter = ('publisher','publication_date') admin.site.register(models.Publisher) admin.site.register(models.Author) admin.site.register(models.Book,BookAdmin)
4.2.查看过滤
5.增加可编辑选项
5.1.修改admin
from django.contrib import admin # Register your models here. from fly import models class BookAdmin(admin.ModelAdmin):
//增加id列 list_display = ('id','name','publisher','publication_date') search_fields = ('name','publisher__name') list_filter = ('publisher','publication_date')
//可编辑选项 list_editable = ('name','publication_date') admin.site.register(models.Publisher) admin.site.register(models.Author) admin.site.register(models.Book,BookAdmin)
5.2.进行编辑
保存编辑:
6.添加分页
list_per_page = 6
查看效果:
7.编辑多对多选项
7.1.编辑admin
from django.contrib import admin # Register your models here. from fly import models class BookAdmin(admin.ModelAdmin): list_display = ('id','name','publisher','publication_date') search_fields = ('name','publisher__name') list_filter = ('publisher','publication_date') list_editable = ('name','publication_date') list_per_page = 6
//编辑多选,只能是多对多 filter_horizontal = ('authors',) admin.site.register(models.Publisher) admin.site.register(models.Author) admin.site.register(models.Book,BookAdmin)
7.2.查看效果
8.批量修改状态
8.1.增加数据库字段,增加状态字段,编辑models
class Book(models.Model): name = models.CharField(max_length=20) authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher) publication_date = models.DateField()
//选项字段 status_choice = ( ('published','出版咧'), ('producing','么出版'), ('forbidden','禁书') )
//状态字段 status = models.CharField(choices=status_choice,max_length=32) def __str__(self): return "<%s>" %(self.name)
8.2.运行添加
8.3.修改状态字段
已经有的数据,没有状态字段,所以必须给已经有的数据增加一个默认字段
class Book(models.Model): name = models.CharField(max_length=20) authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher) publication_date = models.DateField() status_choice = ( ('published','出版咧'), ('producing','么出版'), ('forbidden','禁书') ) status = models.CharField(choices=status_choice,max_length=32,default='producing') def __str__(self): return "<%s>" %(self.name)
8.4.再增加数据库字段
查看是否添加完成:
8.5.增加到页面展示
8.6.配置admin action
参考:https://docs.djangoproject.com/en/1.11/ref/contrib/admin/actions/
8.6.1.修改admin
from django.contrib import admin # Register your models here. from fly import models
//定义更新状态方法 def make_published(modeladmin,request,queryset): queryset.update(status='forbidden') class BookAdmin(admin.ModelAdmin): list_display = ('id','name','publisher','publication_date','status') search_fields = ('name','publisher__name') list_filter = ('publisher','publication_date') list_editable = ('name','publication_date') list_per_page = 6 filter_horizontal = ('authors',)
//动作应用上定义的方法 actions = [make_published] admin.site.register(models.Publisher) admin.site.register(models.Author) admin.site.register(models.Book,BookAdmin)
8.6.2.更新数据
8.6.3.查看更新结果
9.给状态添加颜色
9.1.修改admin,新增方法color_status
//格式化必须导入方法
from django.utils.html import format_html
class Book(models.Model): name = models.CharField(max_length=20) authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher) publication_date = models.DateField() status_choice = ( ('published','出版咧'), ('producing','么出版'), ('forbidden','禁书') ) status = models.CharField(choices=status_choice,max_length=32,default='producing') def __str__(self): return "<%s>" %(self.name) def color_status(self): if self.status == 'published': form_st = format_html('<span style="padding: 2px;background-color: #f1cf6b">出版咧</span>') elif self.status == 'producing': form_st = format_html('<span style="padding: 2px;background-color: aqua">么出版</span>') elif self.status == 'forbidden': form_st = format_html('<span style="padding: 2px;background-color: deeppink">禁书</span>') return form_st
9.2.修改admin
新增color_status去掉status