• 7 stark组件介绍、配置、2层url


    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
    View Code

     

    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
    View Code

     

    makemigrations
    migrate
    createsuperuser (alex 1234qwer)

    2 stark组件开发

    仿django自带得admin组件。

     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()   # 单例对象
    View Code

     

    3. settings中配置'  stark.apps.StarkConfig'

     

    from django.apps import AppConfig
    from django.utils.module_loading import autodiscover_modules
    
    class App01Config(AppConfig):
        name = 'app01'
    
        # 程序启动时,扫描app下得指定文件(starkadmin.py)并执行
        def ready(self):
            autodiscover_modules('starkadmin')

    4.models.py (一对一,一对多,多对多)

    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",to_field="nid", on_delete=models.CASCADE)
    
        def __str__(self):
            return self.name
    
    
    class AuthorDetail(models.Model):
        nid = models.AutoField(primary_key=True)
        birthday = models.DateField()
        telephone = models.BigIntegerField()
        addr = models.CharField(max_length=64)
    
        def __str__(self):
            return str(self.telephone)
    
    
    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)
        title = models.CharField(verbose_name='名称', max_length=32)
        publishDate = models.DateField()
        price = models.DecimalField(verbose_name='价格', max_digits=5,decimal_places=2)
    
        # 与Publish建立一对多的关系,外键字段建立在多的一方
        publish = models.ForeignKey(to="Publish", to_field="nid", on_delete=models.CASCADE)
        # 与Author表建立多对多的关系,ManyToManyField可以建在两个模型中的任意一个,自动创建第三张表
        authors = models.ManyToManyField("Author")
    
        def __str__(self):
            return self.title
    View Code

    5、starkadmin中注册(仿admin)

     

    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()   # 单例对象
    View Code

     

     

    2、不同的model表,显示不同的url

     3、ModelStark

    ModelStark()
    self.model:用户访问的模型表

    4、构造2层urls

      

    # -*- coding: utf-8 -*-
    # @Time    : 2018/08/17 0017 14:46
    # @Author  : Venicid
    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
    
    
    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 = []
            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))
                """
                   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()   # 单例对象

     

    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

      

  • 相关阅读:
    jQuery过滤器 过滤器
    查询总结
    ado.net
    禅修程序员十诫
    Asp.net中Bind()和Eval()的区别
    什么是好代码?
    12 个有效的提高编程技能的方法
    Visual Studio各种版本之间的转换工具
    程序员的培养
    session和cookie的区别和联系!
  • 原文地址:https://www.cnblogs.com/venicid/p/9493474.html
Copyright © 2020-2023  润新知