10.17正式开发stark项目(二)

2018-10-17 11:09:48

orm补充参考连接: https://www.cnblogs.com/yuanchenqi/articles/8963244.html

model 进阶 参考连接: https://www.cnblogs.com/yuanchenqi/articles/7570003.html

现在的stark已经增加用不部分定制类信息:

用户可以定制表头显示,中文显示什么的

都是在stark   的ModelStark这个类里面实现了 各种url解耦,各种视图解耦,然后用户的配置类继承了这个类,

关于配置方法,如果用户没有配置则是默认用该类的默认设置,如果用户配置了,则用用户的加了一些判断

关于每个url使用了反向解析,避免了前端页面写死url的事情!

整体都是面向对象,类的使用 解耦!仿照的admin!

在代码中有注释,思路很清晰!顺着url一点一点向下找就好啦!

明天复习Django,明晚上看视频!白天该把博客整理一下啦!直接整理Django!

越努力越幸运!永远不要高估自己!!!

 先补充一下知识点:

from django.test import TestCase

# Create your tests here.


# class  A(object):
#
#     x=12
#
#     def xxx(self):
#         print(self.x)
#
#
# class B(A):
#     y=5
#
# b=B()
# b.xxx()

#######################################

#
# class Person(object):
#     def __init__(self,name):
#         self.name=name
#
# alex=Person("alex")
#
# s="name"
#
#
# print(getattr(alex,s))

########################################

# class Person(object):
#     def __init__(self,name):
#         self.name=name
#
#     def eat(self):
#         print(self)
#         print("eat....")

# 实例方法
# egon=Person("egon")
# egon.eat()

# 函数
# Person.eat(123)

########################################

# class Person(object):
#
#     def __init__(self,name):
#         self.name=name
#
#     def __str__(self):
#         return self.name
#
# alex=Person("alex")
#
# print(alex.__str__())
# print(str(alex))

########################################


def foo():
    return

print(foo.__name__)

app01/server.py

from stark.service.stark import site,ModelStark
from .models import *
from django.forms import ModelForm


class BookModelForm(ModelForm):
    class Meta:
        model = Book
        fields = "__all__"

        labels = {
            "title": "书籍名称",
            "price": "价格"
        }


class BookConfig(ModelStark):
    list_display = ["title","price","publishDate"]
    modelform_class=BookModelForm


site.register(Book, BookConfig)
site.register(Publish)
site.register(Author)
site.register(AuthorDetail)

stark/server/stark.py

from django.conf.urls import url
from django.shortcuts import render, redirect
from django.urls import reverse
from django.utils.safestring import mark_safe
from django.forms import ModelForm
from django.forms import widgets as wid


class ModelStark(object):
    # 默认的list_play[]
    list_display = ["__str__", ]
    list_display_links = []
    modelform_class = None

    def __init__(self, model, site):
        self.model = model
        self.site = site

    # 配置表头: 删除 编辑,复选框
    def edit(self, obj=None, header=False):
        """编辑"""
        if header:
            return "操作"
        # return mark_safe("<a href='%s/change'>编辑</a>"%obj.pk)
        _url = self.get_change_url(obj)
        return mark_safe("<a href='%s'>编辑</a>" % _url)

    def deletes(self, obj=None, header=False):
        """删除"""
        if header:
            return "操作"
        # return mark_safe("<a href='%s/change'>编辑</a>"%obj.pk)
        _url = self.get_delete_url(obj)
        return mark_safe("<a href='%s'>删除</a>" % _url)

    def checkbox(self, obj=None, header=False):
        """复选框"""
        if header:
            return mark_safe('<input id="choice" type="checkbox">')
        return mark_safe('<input class="choice_item" type="checkbox">')

    # 获取配置类的表头信息
    def get_modelform_class(self):
        """获取表的配置类"""
        if not self.modelform_class:
            # 如果表的配置类为空
            class ModelFormDemo(ModelForm):
                class Meta:
                    model = self.model
                    fields = "__all__"
                    labels = {
                        ""
                    }
            return ModelFormDemo
        else:
            return self.modelform_class

    # 添加的视图函数
    def add_view(self, request):
        ModelFormDemo = self.get_modelform_class()
        if request.method == "POST":
            form = ModelFormDemo(request.POST)
            if form.is_valid():
                form.save()
                return redirect(self.get_list_url())

            return render(request, "add_view.html", locals())

        form = ModelFormDemo()

        return render(request, "add_view.html", locals())

    # 删除的视图函数
    def delete_view(self, request, id):
        url = self.get_list_url()
        if request.method == "POST":
            self.model.objects.filter(pk=id).delete()
            return redirect(url)
        return render(request, "delete_view.html", locals())

    # 编辑的视图函数
    def change_view(self, request, id):
        ModelFormDemo = self.get_modelform_class()
        edit_obj = self.model.objects.filter(pk=id).first()
        if request.method == "POST":
            form = ModelFormDemo(request.POST, instance=edit_obj)
            if form.is_valid():
                form.save()
                return redirect(self.get_list_url())
            return render(request, "add_view.html", locals())
        form = ModelFormDemo(instance=edit_obj)
        return render(request, "change_view.html", locals())

    # 查看的视图函数
    def list_view(self, request):
        print(self.model)  # UserConfig(Userinfo).model
        print("list_dispaly", self.list_display)
        data_list = self.model.objects.all()  # 【obj1,obj2,....】

        # 构建表头
        header_list = []
        # [checkbox,"pk","name","age",edit ,deletes]     【checkbox ,"__str__", edit ,deletes】
        print("header", self.new_list_play())
        for field in self.new_list_play():
            if callable(field):
                # header_list.append(field.__name__)
                val = field(self, header=True)
            else:
                if field == "__str__":
                    header_list.append(self.model._meta.model_name.upper())
                else:
                    # header_list.append(field)
                    val = self.model._meta.get_field(field).verbose_name
                    header_list.append(val)

        # 构建表单数据
        new_data_list = []
        for obj in data_list:
            temp = []
            for filed in self.new_list_play():  # ["__str__",]      ["pk","name","age",edit]
                if callable(filed):
                    val = filed(self, obj)
                else:
                    val = getattr(obj, filed)
                    if filed in self.list_display_links:
                        # "app01/userinfo/(\d+)/change"
                        _url = self.get_change_url(obj)
                        val = mark_safe("<a href='%s'>%s</a>" % (_url, val))
                temp.append(val)
            new_data_list.append(temp)

        '''
        [
            [1,"alex",12],
            [1,"alex",12],
            [1,"alex",12],
            [1,"alex",12],
                 ]
        '''
        print(new_data_list)
        # 构建一个查看URL
        add_url = self.get_add_url()
        return render(request, "list_view.html", locals())

    #  获取用户配置类里面的list_play[]
    def new_list_play(self):
        temp = []
        temp.append(ModelStark.checkbox)
        temp.extend(self.list_display)
        if not self.list_display_links:
            temp.append(ModelStark.edit)
        temp.append(ModelStark.deletes)
        return temp

    """把url进行反向解析,解耦到各自的函数中,函数中直接返回了对应的url"""
    # 获取修改页面的url
    def get_change_url(self, obj):
        model_name = self.model._meta.model_name
        app_label = self.model._meta.app_label

        _url = reverse("%s_%s_change" % (app_label, model_name), args=(obj.pk,))

        return _url

    # 获删除改页面的url
    def get_delete_url(self, obj):
        model_name = self.model._meta.model_name
        app_label = self.model._meta.app_label

        _url = reverse("%s_%s_delete" % (app_label, model_name), args=(obj.pk,))

        return _url

    # 获取添加页面的url
    def get_add_url(self):

        model_name = self.model._meta.model_name
        app_label = self.model._meta.app_label

        _url = reverse("%s_%s_add" % (app_label, model_name))

        return _url

    # 获取查看页面的url
    def get_list_url(self):

        model_name = self.model._meta.model_name
        app_label = self.model._meta.app_label

        _url = reverse("%s_%s_list" % (app_label, model_name))

        return _url

    # 二级url分发函数
    def get_urls_2(self):

        temp = []

        model_name = self.model._meta.model_name
        app_label = self.model._meta.app_label

        temp.append(url(r"^add/", self.add_view, name="%s_%s_add" % (app_label, model_name)))
        temp.append(url(r"^(\d+)/delete/", self.delete_view, name="%s_%s_delete" % (app_label, model_name)))
        temp.append(url(r"^(\d+)/change/", self.change_view, name="%s_%s_change" % (app_label, model_name)))
        temp.append(url(r"^$", self.list_view, name="%s_%s_list" % (app_label, model_name)))

        return temp

    @property
    def urls_2(self):
        print(self.model)
        return self.get_urls_2(), None, None


class StarkSite(object):
    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)

    # 一级分发url函数
    def get_urls(self):
        temp = []
        for model, stark_class_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), stark_class_obj.urls_2))

            '''
            url(r"^app01/userinfo/",UserConfig(Userinfo).urls_2),
            url(r"^app01/book/",ModelStark(Book).urls_2), 


            '''
        return temp

    @property
    def urls(self):

        return self.get_urls(), None, None

# 创建stark的一个单例对象
site = StarkSite()

app01/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",on_delete=models.CASCADE)

    def __str__(self):
        return self.name

class AuthorDetail(models.Model):

    nid = models.AutoField(primary_key=True)
    birthday=models.DateField(auto_now_add=True)
    telephone=models.BigIntegerField()
    addr=models.CharField( max_length=64)

    def __str__(self):
        return 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( 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

 

posted @ 2018-10-17 12:07  我想喝杨枝甘露~  阅读(205)  评论(0编辑  收藏  举报