• 仿照admin实现一个自定义的增删改查的组件


    1、首先,创建三个项目,app01,app02,stark,在settings里边记得配置。然后举例:在app01的model里边写表,用的db.sqlite3,所以数据库不用再settings里边配置。

    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.DateField()
        telephone = models.BigIntegerField()
        addr = models.CharField(max_length=64)
    
    
    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(max_length=32)
        publishDate = models.DateField()
        price = models.DecimalField(max_digits=5, decimal_places=2)
    
        # 与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

    2、启动:类似于admin

    在stark文件夹下的apps里边写:

    from django.apps import AppConfig
    # 经源码分析,admin就是这样先导入这个
    from django.utils.module_loading import autodiscover_modules
    
    
    class StarkConfig(AppConfig):
        name = 'stark'
    
        def ready(self):
            autodiscover_modules("stark")

    这是因为,程序一启动,先执行settings.py中的install_apps里边的模块。具体步骤详看有道云笔记。

    3、注册以及url的设计

    首先在stark的下边创建一个service包,创建一个sites.py,

    里边放全局类以及默认配置类

    from django.conf.urls import url
    from django.shortcuts import HttpResponse, render, redirect
    
    
    class ModelStark(object):
        """
        默认配置类
        """
        list_display = []
    
        def __init__(self, model):
            self.model = model
    
        def listview(self, request):
            print(self)  # 当前访问模型表的配置类对象
         print(self.model)  # 当前访问模型表
            data_list = self.model.objects.all()
            print(self.list_display)
            return render(request, "list_view.html", {"data_list": data_list})
    
        def addview(self, request):
            return HttpResponse("addview")
    
        def changeview(self, request, id):
            return HttpResponse("changeview")
    
        def delview(self, request, id):
            return HttpResponse("delview")
    
        def get_urls(self):
            temp = [
                url(r"^$", self.listview),
                url(r"add/$", self.addview),
                url(r"(d+)/change/$", self.changeview),
                url(r"(d+)/delete/$", self.delview),
    
            ]
            return temp
    
        @property
        def urls(self):
            return self.get_urls(), None, None
    
    
    class AdminSite(object):
        """
            stark组件的全局类
        """
    
        def __init__(self):
            self._registry = {}
    
        def register(self, model, admin_class=None):
            # 设置配置类
            if not admin_class:
                admin_class = ModelStark
            self._registry[model] = admin_class(model)
    
        def get_urls(self):
            temp = []
            for model, config_obj in self._registry.items():
                model_name = model._meta.model_name
                app_label = model._meta.app_label
                temp.append(url(r"%s/%s/" % (app_label, model_name), config_obj.urls))
                # config_obj 获取的就是每个for循环中的BookConfig(Book),publish,author遍历的对象
                '''
                          temp=[
    
                              #(1) url(r"app01/book/",BookConfig(Book).urls)
                              #(2) url(r"app01/book/",(BookConfig(Book).get_urls(), None, None))
                              #(3) url(r"app01/book/",([
                                                              url(r"^$", BookConfig(Book).listview),
                                                              url(r"add/$", BookConfig(Book).addview),
                                                              url(r"(d+)/change/$", BookConfig(Book).changeview),
                                                              url(r"(d+)/delete/$", BookConfig(Book).delview),
                                                       ], None, None))
    
                              ###########
    
                              # url(r"app01/publish/",([
                                                              url(r"^$", ModelStark(Publish).listview),
                                                              url(r"add/$",  ModelStark(Publish).addview),
                                                              url(r"(d+)/change/$",  ModelStark(Publish).changeview),
                                                              url(r"(d+)/delete/$",  ModelStark(Publish).delview),
                                                       ], None, None))
                          ]
                          '''
    
            return temp
    
        @property
        def urls(self):
            return self.get_urls(), None, None
    
    
    site = AdminSite()
  • 相关阅读:
    MOSS中的WebPart开发
    坚持学习WF(8):本地服务之调用外部方法
    坚持学习WF(9):本地服务之事件处理
    MOSS中如何自定义WebService
    uHub 0.4.1 发布,ADC 网络枢纽
    电商网站的宕机案例分析
    JID 2.0.1 发布,高性能的 Java 序列化库
    YaCy 1.2 发布,基于P2P的分布式Web搜索引擎
    Notepad++ 6.2.0 正式版
    Windows上 IE10 最快,Mac上Chrome 19最快
  • 原文地址:https://www.cnblogs.com/hnlmy/p/9551150.html
Copyright © 2020-2023  润新知