10.20stark组件已经完工

2018-10-20 19:37:31

stark组件已经做完!基本上和Django的admin一样!

放上github连接:https://github.com/TrueNewBee/pythonDemo/blob/master/stark.rar

放上正版的stark组件: https://github.com/TrueNewBee/pythonDemo/blob/master/stark%E6%BA%90%E7%89%88%E6%9C%AC.zip

2018-10-21 21:49:59 由于直接把该项目放到crm中有bug,所以用crm源码修改了一下!然后放上新的源码优化了一下!

 

stark组件已经完成,明天整理Django博客!

后面的就是crm项目啦!

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

知识点  test.py

子类继承父类 , 然后和父类的类型一样 isinstance()

modelForm 把  model.Model 转换成 form.Form

ChoiceFiled
ModelChoiceFiled(ChoiceFiled) ---- select(单选)
MultiModelChoiceFiled (ModelChoiceFiled)----select(多选)



class Book(model.Model):
    title = models.CharField(max_length=32)
    price = models.IntegerField()
    publish=model.Foreignkey("Publish")
    authors=model.ManyToMany("Author")




from django.forms import ModelForm
class BookForm(ModelForm):
    class Meta:
        model=Book
        fields="__all__"
        
        
        
    
from django import forms
class BookForm(forms.Form):
    title=forms.CharField(max_length=32)
    price=forms.IntegerField()
    publish = forms.ModelChoiceFiled("Publish")
    authors = forms.ModelMultipleChoiceField("Author")
 
 
 
form=BookForm()


for i in form:
    if isinstance(i,ModelChoiceFiled):
        pass 
  
        
'''

 

pop功能:

 

1 如何在一对多和多对多字段后渲染 +

2 +对应的跳转路径

上述两步实现逻辑

def add_view(self, request):
    # 实例化form类对象
    ModelFormDemo = self.get_modelform_class()
    form = ModelFormDemo()
    for bfield in form:
        # 这个可以看源码,然后类调用所需属性
        from django.forms.boundfield import BoundField
        print(bfield.field)             # 字段对象
        print("name",bfield.name)       # 字段名(字符串)
        print(type(bfield.field))       # 字段类型
        # 看源码可得 多对多和一对多是ModelChoiceFiled的类型
        from django.forms.models import ModelChoiceField
        if isinstance(bfield.field, ModelChoiceField):
            # 增加一个属性,传给前端做判断,是否显示这个 +按钮
            bfield.is_pop = True
            print("=======>", bfield.field.queryset.model) # 一对多或者多对多字段的关联模型表
            # 通过下面两个方法,找到表和app名字
            related_model_name = bfield.field.queryset.model._meta.model_name
            related_app_label = bfield.field.queryset.model._meta.app_label
            # 拼接url传给前端
            _url = reverse("%s_%s_add" % (related_app_label, related_model_name))
            # 创建一个新的属性url 给前端调用
            bfield.url = _url+"?pop_res_id=id_%s" % bfield.name

上面是get请求,下面是这个函数post请求的逻辑

# POST请求
        if request.method == "POST":
            form = ModelFormDemo(request.POST)
            if form.is_valid():
                obj = form.save()       # 保存数据,并返回一个obj
                pop_res_id = request.GET.get("pop_res_id")
                # 判断是点击+按钮带参数访问,还是通过add页面直接访问的
                if pop_res_id:
                    res = {"pk": obj.pk, "text": str(obj), "pop_res_id": pop_res_id}
                    return render(request, "pop.html", {"res": res})
                else:
                    return redirect(self.get_list_url())
        return render(request, "add_view.html", locals())

 


3 保存添加记录同时,将原页面的对应的下拉菜单中添加该记录
通过js方法!

from.html

pop.html  (作用就是一个桥梁,传给父类页面相应参数,然后关闭)

add.html(接受子页面传入的参数,然后通过jQuery方法把传入的数据直接添加到select框中默认选中)

然后附上这个stark组件的主要代码!主要看逻辑实现!!想看源码就去github下一下!源码里面都注释好啦!!!!!

 stark/stark.py

from django.conf.urls import url
from django.shortcuts import render, redirect
from django.urls import reverse
from django.db.models import Q
from django.utils.safestring import mark_safe
from stark.utils.page import Pagination
from django.db.models.fields.related import ForeignKey
from django.db.models.fields.related import ManyToManyField
from django.forms import ModelForm
import copy

"""
Stark组件!
2018-10-21 20:21:41
功能简介:
由于原来做的stark有bug,所以修改了一下,setting注册就可以使用完美仿照admin
*********
1. 使用方法和Django的admin一样,需要在stark里面注册,详情看app01/stark.py
2. 实现了对不同表的url的各级分发
3. 用户可以自定义配置表的现实信息 详情可以看app01/stark.py
4. 实现了对表添加数据pop的功能!
5. 最强大就是,你可以拿去直接用,和admin一样,而且不需要超级用户!
2333333333333333333333333333333
"""


# List视图用于解耦的一个类
class ShowList(object):
# 这是一个配置类的对象初始化
def __init__(self, config, data_list, request):
self.config = config
self.data_list = data_list
self.request = request
# 分页
data_count = self.data_list.count()
current_page = int(self.request.GET.get("page", 1))
base_path = self.request.path
self.pagination = Pagination(current_page, data_count, base_path, self.request.GET, per_page_num=10,
pager_count=11,)
self.page_data = self.data_list[self.pagination.start:self.pagination.end]
# actions 获取actions这个配置类的列表
self.actions = self.config.new_actions() # [patch_init,]

# 处理filter字段连接
def get_filter_linktags(self):
"""用了两次for循环,在算法上有点缀余!不过可以用类或函数封装只是懒-.-能力欠缺!"""
print("list_filter:", self.config.list_filter)
link_dic = {}

for filter_field in self.config.list_filter: # ["title","publish","authors",]
params = copy.deepcopy(self.request.GET)
cid = self.request.GET.get(filter_field, 0)
print("filter_field", filter_field) # "publish"
# 通过_meta.get_field方法,获取该表名对象
filter_field_obj = self.config.model._meta.get_field(filter_field)

# 判断一下 如果是多对多或一对多类型的
if isinstance(filter_field_obj, ForeignKey) or isinstance(filter_field_obj, ManyToManyField):
# 拿到表的所有QuerySet对象
data_list = filter_field_obj.rel.to.objects.all() # 【publish1,publish2...】
else:
# 这个则是自定义过滤字段
data_list = self.config.model.objects.all().values("pk", filter_field)
print("data_list", data_list)
temp = []
# 处理 全部标签
if params.get(filter_field):
# 如果url如果存在参数 则del
del params[filter_field]
temp.append("全部" % params.urlencode())
else:
# 反之加上class 增加颜色
temp.append("全部")

# 处理 数据标签
for obj in data_list:
# 循环列表中每个QuerySet的对象然后取到相应的值
if isinstance(filter_field_obj, ForeignKey) or isinstance(filter_field_obj, ManyToManyField):
pk = obj.pk
text = str(obj)
params[filter_field] = pk
else: # data_list= [{"pk":1,"title":"go"},....]
pk = obj.get("pk")
text = obj.get(filter_field)
params[filter_field] = text

_url = params.urlencode()
if cid == str(pk) or cid == text:
link_tag = "%s" % (_url, text)
else:
link_tag = "%s" % (_url, text)

temp.append(link_tag)
link_dic[filter_field] = temp
return link_dic

# 获取下拉框 用户配置的action_list
def get_action_list(self):
temp = []
for action in self.actions:
# [{"name":""patch_init,"desc":"批量初始化"}]
temp.append({
"name": action.__name__,
"desc": action.short_description
})
return temp

# 构建表头
def get_header(self):
# 构建表头
header_list = []
print("header", self.config.new_list_play())
# [checkbox,"pk","name","age",edit ,deletes] 【checkbox ,"__str__", edit ,deletes】

for field in self.config.new_list_play():
if callable(field):
# header_list.append(field.__name__)
val = field(self.config, header=True)
header_list.append(val)
else:
if field == "__str__":
header_list.append(self.config.model._meta.model_name.upper())
else:
# header_list.append(field)
val = self.config.model._meta.get_field(field).verbose_name
header_list.append(val)
return header_list

# 构建表单数据
def get_body(self):
# 构建表单数据
new_data_list = []
for obj in self.page_data:
temp = []
# 切记不可把循环对象命名一样!!容易出bug而且找不到
for filed in self.config.new_list_play(): # ["__str__",] ["pk","name","age",edit]
if callable(filed):
print("obj-----:", obj)
val = filed(self.config, obj)
else:
# 这里捕获一下异常,因为默认的list_play里面有__str__ 直接找不到该字段
# 所以直接用getattr方法就行啦!
try:
field_obj = self.config.model._meta.get_field(filed)
if isinstance(field_obj, ManyToManyField):
# getattr()仅取到Object, 然后.all() 则可以取到对象
ret = getattr(obj, filed).all()
t = []
for mobj in ret:
t.append(str(mobj))
val = ",".join(t)
else:
val = getattr(obj, filed)
if filed in self.config.list_display_links:
# "app01/userinfo/(\d+)/change"
_url = self.config.get_change_url(obj)
val = mark_safe("%s" % (_url, val))
except Exception as e:
val = getattr(obj, filed)
temp.append(val)
new_data_list.append(temp)
return new_data_list


'''
[
[1,"alex",12],
[1,"alex",12],
[1,"alex",12],
[1,"alex",12],

]

'''


class ModelStark(object):
list_display = ["__str__", ]
list_display_links = []
modelform_class = None
search_fields = []
actions = []
list_filter = []

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

# 默认的批量删除action
def patch_delete(self, request, queryset):
queryset.delete()
patch_delete.short_description = "批量删除"

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

def deletes(self, obj=None, header=False):
"""删除"""
if header:
return "操作"
# return mark_safe("编辑"%obj.pk)

_url = self.get_delete_url(obj)

return mark_safe("删除" % _url)

def checkbox(self, obj=None, header=False):
"""复选框"""
if header:
return mark_safe('')
# value的值不能写死,
return mark_safe('' % obj.pk)

# 获取配置类的表头信息
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

# 封装的form 方法
def get_new_form(self, form):
for bfield in form:
# 这个可以看源码,然后类调用所需属性
from django.forms.boundfield import BoundField
print(bfield.field) # 字段对象
print("name", bfield.name) # 字段名(字符串)
print(type(bfield.field)) # 字段类型
# 看源码可得 多对多和一对多是ModelChoiceFiled的类型
from django.forms.models import ModelChoiceField
if isinstance(bfield.field, ModelChoiceField):
# 增加一个属性,传给前端做判断,是否显示这个 +按钮
bfield.is_pop = True
print("=======>", bfield.field.queryset.model) # 一对多或者多对多字段的关联模型表
# 通过下面两个方法,找到表和app名字
related_model_name = bfield.field.queryset.model._meta.model_name
related_app_label = bfield.field.queryset.model._meta.app_label
# 拼接url传给前端
_url = reverse("%s_%s_add" % (related_app_label, related_model_name))
# 创建一个新的属性url 给前端调用
bfield.url = _url + "?pop_res_id=id_%s" % bfield.name
return form

# 添加的视图函数
def add_view(self, request):
# 实例化form类对象 方便Django构建form表单
ModelFormDemo = self.get_modelform_class()
form = ModelFormDemo()
# 将form对象传入函数get_new_form() 完成get请求逻辑,防止add_view这个视图里面代码缀余
form = self.get_new_form(form)
# POST请求
if request.method == "POST":
form = ModelFormDemo(request.POST)
if form.is_valid():
obj = form.save() # 保存数据,并返回一个obj
pop_res_id = request.GET.get("pop_res_id")
# 判断是点击+按钮带参数访问,还是通过add页面直接访问的
if pop_res_id:
res = {"pk": obj.pk, "text": str(obj), "pop_res_id": pop_res_id}
return render(request, "pop.html", {"res": res})
else:
return redirect(self.get_list_url())
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()
print("=====id", id)
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())

print("***********", edit_obj)
form = ModelFormDemo(instance=edit_obj)
form = self.get_new_form(form)

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

# 搜索的视图函数
def get_serach_conditon(self, request):
key_word = request.GET.get("q", "")
self.key_word = key_word
search_connection = Q()
if key_word:
# self.search_fields # ["title","price"]
search_connection.connector = "or"
for search_field in self.search_fields:
# search_field+"__contains" ----> title__contains="o" 就是title字段里面包含字母o的
search_connection.children.append((search_field + "__contains", key_word))
return search_connection

# 过滤filter的视图函数
def get_filter_condition(self, request):
filter_condition = Q()
for filter_field, val in request.GET.items():
if filter_field != "page":    # 这里就是为了分页的时候,page不当做参数传过来
filter_condition.children.append((filter_field, val))
return filter_condition

# 查看的视图函数
def list_view(self, request):
if request.method == "POST": # action
print("POST:", request.POST)
action = request.POST.get("action") # patch_init
selected_pk = request.POST.getlist("selected_pk")
action_func = getattr(self, action)
queryset = self.model.objects.filter(pk__in=selected_pk)
ret = action_func(request, queryset)
# return ret
# 获取serach的Q对象
search_connection = self.get_serach_conditon(request)

# 获取filter构建Q对象

filter_condition = self.get_filter_condition(request)

# 筛选获取当前表所有数据
data_list = self.model.objects.all().filter(search_connection).filter(filter_condition) # 【obj1,obj2,....】

# 按这ShowList展示页面
showlist = ShowList(self, data_list, request)

# 构建一个查看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

# 获取用户配置类里面的actions 这个列表
def new_actions(self):
temp = []
temp.append(ModelStark.patch_delete)
temp.extend(self.actions)
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
print("obj===========", obj)
_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 extra_url(self):
return []

# 二级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)))
# 在这继承extra_url()的temp ,这样默认temp为空,其他的表的配置类没有写则无扩展的url,如果有的话则实现了扩展
temp.extend(self.extra_url())
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/stark.py

# 现在重写的部分配置信息!
from stark.service.stark import site, ModelStark
from django.utils.safestring import mark_safe
from django.conf.urls import url
from django.shortcuts import redirect
from .models import *
"""
可以配置字段:
1. list_display[] 可以添加自定义展示字段,也可以添加函数名
2. 父类提供的添加该表额外url的接口 def extra_url 重写这个方法即可
"""


class UserConfig(ModelStark):
# 自定义展示字段 list_display[]
list_display = ["name", "email", "depart"]


class ClassConfig(ModelStark):
# 自定义一个展示函数,然后添加到list_display中
def display_classname(self, obj=None, header=False):
if header:
return "班级名称"
class_name = "%s(%s)" % (obj.course.name, str(obj.semester))
return class_name
list_display = [display_classname, "tutor", "teachers"]


class CusotmerConfig(ModelStark):

def display_gender(self, obj=None, header=False):
if header:
return "性别"
return obj.get_gender_display()

def display_course(self, obj=None, header=False):
if header:
return "咨询课程"
temp = []
for course in obj.course.all():
s = "%s " % (
obj.pk, course.pk, course.name,)
temp.append(s)
return mark_safe("".join(temp))
list_display = ["name", display_gender, display_course, "consultant", ]

def cancel_course(self, request, customer_id, course_id):
print(customer_id, course_id)
obj = Customer.objects.filter(pk=customer_id).first()
obj.course.remove(course_id)
return redirect(self.get_list_url())

# 父类给出的添加额外url的接口
def extra_url(self):
temp = []
temp.append(url(r"cancel_course/(\d+)/(\d+)", self.cancel_course))
return temp


site.register(UserInfo, UserConfig)
site.register(ClassList, ClassConfig)
site.register(Customer, CusotmerConfig)
site.register(Department)
site.register(Course)
site.register(ConsultRecord)
site.register(CourseRecord)
site.register(StudyRecord)
site.register(Student)
site.register(School)

"""
原始配置信息! 下面的可选配置选项上面都有只是没写出来!
from
stark.service.stark import site,ModelStark from django.shortcuts import HttpResponse 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", "publish", "authors"] # 自定义设置字段为连接 list_display_links = ["title"] modelform_class = BookModelForm # 自定义搜索字段 search_fields = ["title", "price"] def patch_init(self, request, queryset): print(queryset) queryset.update(price=123) return HttpResponse("批量初始化OK") patch_init.short_description = "批量初始化" # 自定义处理函数 actions = [patch_init] # 自定义筛选字段 list_filter=["title","publish","authors",] site.register(Book, BookConfig) site.register(Publish) site.register(Author) site.register(AuthorDetail)
"""

app01/models.py

from django.db import models

# Create your models here.

from django.db import models

# Create your models here.


from django.db import models

# Create your models here.

from django.db import models

class Department(models.Model):
"""
部门表
市场部 1000
销售 1001

"""
title = models.CharField(verbose_name='部门名称', max_length=16)
code = models.IntegerField(verbose_name='部门编号', unique=True, null=False)

def __str__(self):
return self.title


class UserInfo(models.Model):
"""
员工表
"""

name = models.CharField(verbose_name='员工姓名', max_length=16)
username = models.CharField(verbose_name='用户名', max_length=32)
password = models.CharField(verbose_name='密码', max_length=64)
email = models.EmailField(verbose_name='邮箱', max_length=64)

depart = models.ForeignKey(verbose_name='部门', to="Department", to_field="code")

def __str__(self):
return self.name


class Course(models.Model):
"""
课程表
如:
Linux基础
Linux架构师
Python自动化开发精英班
Python自动化开发架构师班
Python基础班
go基础班
"""
name = models.CharField(verbose_name='课程名称', max_length=32)

def __str__(self):
return self.name


class School(models.Model):
"""
校区表
如:
北京沙河校区
上海校区

"""
title = models.CharField(verbose_name='校区名称', max_length=32)

def __str__(self):
return self.title


class ClassList(models.Model):
"""
班级表
如:
Python全栈 面授班 5期 10000 2017-11-11 2018-5-11
"""
school = models.ForeignKey(verbose_name='校区', to='School')
course = models.ForeignKey(verbose_name='课程名称', to='Course')

semester = models.IntegerField(verbose_name="班级(期)")
price = models.IntegerField(verbose_name="学费")
start_date = models.DateField(verbose_name="开班日期")
graduate_date = models.DateField(verbose_name="结业日期", null=True, blank=True)
memo = models.CharField(verbose_name='说明', max_length=256, blank=True, null=True, )
# teachers = models.ManyToManyField(verbose_name='任课老师', to='UserInfo',limit_choices_to={'depart_id__in':[1003,1004],})
teachers = models.ManyToManyField(verbose_name='任课老师', to='UserInfo',related_name="abc",limit_choices_to={"depart__in":[1002,1005]})
tutor = models.ForeignKey(verbose_name='班主任', to='UserInfo', related_name='classes',limit_choices_to={"depart":1001})

def __str__(self):
return "{0}({1}期)".format(self.course.name, self.semester)


class Customer(models.Model):
"""
客户表
"""
qq = models.CharField(verbose_name='qq', max_length=64, unique=True, help_text='QQ号必须唯一')

name = models.CharField(verbose_name='学生姓名', max_length=16)
gender_choices = ((1, '男'), (2, '女'))
gender = models.SmallIntegerField(verbose_name='性别', choices=gender_choices)

education_choices = (
(1, '重点大学'),
(2, '普通本科'),
(3, '独立院校'),
(4, '民办本科'),
(5, '大专'),
(6, '民办专科'),
(7, '高中'),
(8, '其他')
)
education = models.IntegerField(verbose_name='学历', choices=education_choices, blank=True, null=True, )
graduation_school = models.CharField(verbose_name='毕业学校', max_length=64, blank=True, null=True)
major = models.CharField(verbose_name='所学专业', max_length=64, blank=True, null=True)

experience_choices = [
(1, '在校生'),
(2, '应届毕业'),
(3, '半年以内'),
(4, '半年至一年'),
(5, '一年至三年'),
(6, '三年至五年'),
(7, '五年以上'),
]
experience = models.IntegerField(verbose_name='工作经验', blank=True, null=True, choices=experience_choices)
work_status_choices = [
(1, '在职'),
(2, '无业')
]
work_status = models.IntegerField(verbose_name="职业状态", choices=work_status_choices, default=1, blank=True,
null=True)
company = models.CharField(verbose_name="目前就职公司", max_length=64, blank=True, null=True)
salary = models.CharField(verbose_name="当前薪资", max_length=64, blank=True, null=True)

source_choices = [
(1, "qq群"),
(2, "内部转介绍"),
(3, "官方网站"),
(4, "百度推广"),
(5, "360推广"),
(6, "搜狗推广"),
(7, "腾讯课堂"),
(8, "广点通"),
(9, "高校宣讲"),
(10, "渠道代理"),
(11, "51cto"),
(12, "智汇推"),
(13, "网盟"),
(14, "DSP"),
(15, "SEO"),
(16, "其它"),
]
source = models.SmallIntegerField('客户来源', choices=source_choices, default=1)
referral_from = models.ForeignKey(
'self',
blank=True,
null=True,
verbose_name="转介绍自学员",
help_text="若此客户是转介绍自内部学员,请在此处选择内部学员姓名",
related_name="internal_referral"
)
course = models.ManyToManyField(verbose_name="咨询课程", to="Course")

status_choices = [
(1, "已报名"),
(2, "未报名")
]
status = models.IntegerField(
verbose_name="状态",
choices=status_choices,
default=2,
help_text=u"选择客户此时的状态"
)

consultant = models.ForeignKey(verbose_name="课程顾问", to='UserInfo', related_name='consultanter',
limit_choices_to={'depart_id': 1001})

date = models.DateField(verbose_name="咨询日期", auto_now_add=True)
recv_date = models.DateField(verbose_name="当前课程顾问的接单日期", null=True)
last_consult_date = models.DateField(verbose_name="最后跟进日期", )

def __str__(self):
return "姓名:{0},QQ:{1}".format(self.name, self.qq, )


class ConsultRecord(models.Model):
"""
客户跟进记录
"""
customer = models.ForeignKey(verbose_name="所咨询客户", to='Customer')
consultant = models.ForeignKey(verbose_name="跟踪人", to='UserInfo')
date = models.DateField(verbose_name="跟进日期", auto_now_add=True)
note = models.TextField(verbose_name="跟进内容...")

def __str__(self):
return self.customer.name + ":" + self.consultant.name


class Student(models.Model):
"""
学生表(已报名)
"""
customer = models.OneToOneField(verbose_name='客户信息', to='Customer')

username = models.CharField(verbose_name='用户名', max_length=32)
password = models.CharField(verbose_name='密码', max_length=64)
emergency_contract = models.CharField(max_length=32, blank=True, null=True, verbose_name='紧急联系人')

class_list = models.ManyToManyField(verbose_name="已报班级", to='ClassList', blank=True)
company = models.CharField(verbose_name='公司', max_length=128, blank=True, null=True)
location = models.CharField(max_length=64, verbose_name='所在区域', blank=True, null=True)
position = models.CharField(verbose_name='岗位', max_length=64, blank=True, null=True)
salary = models.IntegerField(verbose_name='薪资', blank=True, null=True)
welfare = models.CharField(verbose_name='福利', max_length=256, blank=True, null=True)
date = models.DateField(verbose_name='入职时间', help_text='格式yyyy-mm-dd', blank=True, null=True)
memo = models.CharField(verbose_name='备注', max_length=256, blank=True, null=True)

def __str__(self):
return self.username


class CourseRecord(models.Model):
"""
上课记录表
"""
class_obj = models.ForeignKey(verbose_name="班级", to="ClassList")
day_num = models.IntegerField(verbose_name="节次", help_text=u"此处填写第几节课或第几天课程...,必须为数字")
teacher = models.ForeignKey(verbose_name="讲师", to='UserInfo',limit_choices_to={"depart_id__in":[1002,1003]})
date = models.DateField(verbose_name="上课日期", auto_now_add=True)

course_title = models.CharField(verbose_name='本节课程标题', max_length=64, blank=True, null=True)
course_memo = models.TextField(verbose_name='本节课程内容概要', blank=True, null=True)
has_homework = models.BooleanField(default=True, verbose_name="本节有作业")
homework_title = models.CharField(verbose_name='本节作业标题', max_length=64, blank=True, null=True)
homework_memo = models.TextField(verbose_name='作业描述', max_length=500, blank=True, null=True)
exam = models.TextField(verbose_name='踩分点', max_length=300, blank=True, null=True)

def __str__(self):
return "{0} day{1}".format(self.class_obj, self.day_num)


class StudyRecord(models.Model):
course_record = models.ForeignKey(verbose_name="第几天课程", to="CourseRecord")
student = models.ForeignKey(verbose_name="学员", to='Student')
record_choices = (('checked', "已签到"),
('vacate', "请假"),
('late', "迟到"),
('noshow', "缺勤"),
('leave_early', "早退"),
)
record = models.CharField("上课纪录", choices=record_choices, default="checked", max_length=64)
score_choices = ((100, 'A+'),
(90, 'A'),
(85, 'B+'),
(80, 'B'),
(70, 'B-'),
(60, 'C+'),
(50, 'C'),
(40, 'C-'),
(0, ' D'),
(-1, 'N/A'),
(-100, 'COPY'),
(-1000, 'FAIL'),
)
score = models.IntegerField("本节成绩", choices=score_choices, default=-1)
homework_note = models.CharField(verbose_name='作业评语', max_length=255, blank=True, null=True)
note = models.CharField(verbose_name="备注", max_length=255, blank=True, null=True)

homework = models.FileField(verbose_name='作业文件', blank=True, null=True, default=None)
stu_memo = models.TextField(verbose_name='学员备注', blank=True, null=True)
date = models.DateTimeField(verbose_name='提交作业日期', auto_now_add=True)

def __str__(self):
return "{0}-{1}".format(self.course_record, self.student)

 

转载于:https://www.cnblogs.com/zhen1996/p/9822871.html

你可能感兴趣的:(python,前端,javascript,ViewUI)