1、django的admin配置
model.py
from django.db import models
# Create your models here.
class UserInfo(models.Model):
name=models.CharField(max_length=32)
age=models.IntegerField()
def __str__(self):
return self.name
class Book(models.Model):
title=models.CharField(max_length=32)
def __str__(self):
return self.title
admin.py配置
from django.contrib import admin
# Register your models here.
from .models import *
class UserAdmin(admin.ModelAdmin):
list_display = ["pk",‘name‘,‘age‘]
list_filter = [‘name‘,‘age‘]
# 定制action具体方法
def func(self,request,queryset):
queryset.update(age=44)
func.short_description = "批量初始化操作"
actions = [func]
admin.site.register(UserInfo,UserAdmin)
admin.site.register(Book)
admin.py
makemigrations migrate createsuperuser (alex 1234qwer)
2 stark组件开发
1、 python manage.py startapp stark
2、stark/service/stark.py (单例对象)
# -*- coding: utf-8 -*-
# @Time : 2018/08/17 0017 14:46
# @Author : Venicid
class ModelStark(object):
def __init__(self,model, site):
self.model = model
self.site = site
class StarkSite(object):
"""site单例类"""
def __init__(self):
self._registry = {}
def register(self,model, stark_class=None):
"""注册"""
if not stark_class:
stark_class = ModelStark
self._registry[model] = stark_class(model,self)
site = StarkSite() # 单例对象
3. settings中配置‘ stark.apps.StarkConfig‘
from django.apps import AppConfig from django.utils.module_loading import autodiscover_modules class StarkConfig(AppConfig): name = ‘stark‘ def ready(self): autodiscover_modules(‘stark‘)
4.models.py (一对一,一对多,多对多)
app01这个app下创建models表
from django.db import models # Create your models here. class Author(models.Model): nid = models.AutoField(primary_key=True) name=models.CharField( max_length=32) age=models.IntegerField() # 与AuthorDetail建立一对一的关系 authorDetail=models.OneToOneField(to="AuthorDetail",on_delete=models.CASCADE) def __str__(self): return self.name class AuthorDetail(models.Model): nid = models.AutoField(primary_key=True) birthday=models.CharField(max_length=64,default="无") telephone=models.BigIntegerField() addr=models.CharField( max_length=64) def __str__(self): return self.addr class Publish(models.Model): nid = models.AutoField(primary_key=True) name=models.CharField( max_length=32) city=models.CharField( max_length=32) email=models.EmailField() def __str__(self): return self.name class Book(models.Model): nid = models.AutoField(primary_key=True,verbose_name="书籍号") title = models.CharField( max_length=32,verbose_name="书籍名") publishDate=models.DateField(verbose_name="出版日期") price=models.DecimalField(max_digits=5,decimal_places=2,verbose_name="价格") # 与Publish建立一对多的关系,外键字段建立在多的一方 publish=models.ForeignKey(to="Publish",to_field="nid",on_delete=models.CASCADE) # 与Author表建立多对多的关系,ManyToManyField可以建在两个模型中的任意一个,自动创建第三张表 authors=models.ManyToManyField(to=‘Author‘,) def __str__(self): return self.title
5、stark中注册
在app01下创建一个stark的名字的Py文件,将创建的模型表注册进去。
6 配置urls,启动
3、2层url分发
1、构造1层url
stark/service/stark.py
# -*- coding: utf-8 -*-
# @Time : 2018/08/17 0017 14:46
# @Author : Venicid
from django.conf.urls import url
class ModelStark(object):
def __init__(self,model, site):
self.model = model
self.site = site
class StarkSite(object):
"""site单例类"""
def __init__(self):
self._registry = {}
def register(self,model, stark_class=None):
"""注册"""
if not stark_class:
stark_class = ModelStark
self._registry[model] = stark_class(model,self)
def get_urls(self):
"""构造一层urls app01/book"""
temp = []
print(self._registry)
for model, stark_class_obj in self._registry.items():
app_label = model._meta.app_label # app01
model_name = model._meta.model_name # book
temp.append(url(r‘^%s/%s‘%(app_label, model_name),([],None,None)))
return temp
@property
def urls(self):
# return [],None,None
return self.get_urls(),None,None
site = StarkSite() # 单例对象
可以通过stak下循环取到不同的app名字和模型表拼接一个个的url.
2、不同的model表,显示不同的url
3、ModelStark
ModelStark()
self.model:用户访问的模型表
4、构造2层urls
from django.conf.urls import url from django.shortcuts import HttpResponse class ModelStark(object): def __init__(self,model, site): self.model = model self.site = site def list_view(self, request):
#查看视图 print(self.model) # <class ‘app01.models.Book‘> 用户访问的模型表 return HttpResponse(‘list_view‘) def add(self, request):
#增加视图 return HttpResponse(‘add‘) def delete(self, request, id):
#删除视图 return HttpResponse(‘delete‘) def change(self, request, id):
#修改视图 return HttpResponse(‘change‘) def get_urls2(self): """构造 add/delete/change""" temp = [] temp.append(url(r‘^$‘, self.list_view)) temp.append(url(r‘^add/‘, self.add)) temp.append(url(r‘^(d+)/delete/‘, self.delete)) temp.append(url(r‘^(d+)/change/‘, self.change)) return temp #还是返回一个列表 @property def urls2(self): return self.get_urls2(), None, None #返回[],None,None,这种指定的格式。 class StarkSite(object): """site单例类""" def __init__(self): self._registry = {} def register(self,model, stark_class=None): """注册""" if not stark_class: stark_class = ModelStark self._registry[model] = stark_class(model,self)
#在这里注意以模型表为键,<class ‘app01.models.Author‘>: <app01.stark.AuthorConfig object at 0x00000154D50F4240> #模型表的配置为值,如果没有配置默认使用ModelStark.
def get_urls(self): """构造一层urls app01/book""" temp = [] for model, stark_class_obj in self._registry.items(): print(model, ‘stark_clas_obj‘, stark_class_obj) # 不同的model模型表 """ <class ‘app01.models.UserInfo‘> ----> <app01.starkadmin.UserConfig object at 0x00000072DDB65198> <class ‘app01.models.Book‘> ----> <stark.service.stark.ModelStark object at 0x00000072DDB65240> """ app_label = model._meta.app_label # app01 model_name = model._meta.model_name # book # temp.append(url(r‘^%s/%s‘%(app_label, model_name),([],None,None))) temp.append(url(r‘^%s/%s‘%(app_label, model_name),stark_class_obj.urls2)) #这里循环一条,调用配置类里面的url2,拼接上增删改查。 """ path(‘app01/userinfo/‘,UserConfig(Userinfo,site).urls2), path(‘app01/book/‘,ModelStark(Book,site).urls2), """ return temp @property def urls(self): # return [],None,None return self.get_urls(),None,None site = StarkSite() # 单例对象
这里注意为什么要用stark_class_obj,因为这个是ModelStark的实例,传入的model是什么,那么self.model就是什么,因为以model为键,这个stark_class_obj为值,参数传入的
是model,所以就能识别出来哪个表的增删改查。
_registry {<class ‘app01.models.Author‘>: <app01.stark.AuthorConfig object at 0x00000154D50F4240>}
4、小结
1. url分发:
url(r‘^stark/‘, ([],None,None))
url(r‘^stark/‘, stark.site.urls)
@property
def urls(self):
return self.get_urls(), None, None
2. 用户可以自定制配置页面,所以调用配置类 stark_class_obj.urls2
# 分发增删改查
temp.append(url(r‘%s/%s/‘%(app_label,model_name), stark_class_obj.urls2))
3.ModelStark
ModelStark()
self.model:用户访问的模型表
model_name = self.model._meta.model_name
app_label = self.model._meta.app_label