17-crm项目-kingadmin,前端展示数据库中不存在的字段

有很多时候都需要前端展示数据库中不存在的字段

怎么做?

比如:有客户,然后需要在右侧加一个报名,这个报名字段就不是数据库的,但是需要这样一个字段按钮,怎么办?

 

第一步加一个函数,

class CustomerAdmin(BaseAdmin):
    list_display = ["id",'qq','name','source','consultant','consult_course','date','status','enroll']  ---这是加到字段里不存在的字段
    list_filters = ['source','consultant','consult_course','status','date']
    search_fields = ['qq','name',"consultant__name"]
    filter_horizontal = ('tags',)
    #model = models.Customer
    list_per_page = 2
    ordering = "qq"
    readonly_fields = ["qq","consultant","tags"]
    #readonly_table = True
    #modelform_exclude_fields = []
    actions = ["delete_selected_objs","test"]
    def test(self,request,querysets):
        print("in test",)
    test.display_name  = "测试动作"

    def enroll(self):
        print("enroll",self.instance)
        if self.instance.status ==0:
            link_name = "报名新课程"
        else:
            link_name = "报名"
        return '''<a href="/crm/customer/%s/enrollment/" > %s</a>''' %(self.instance.id,link_name)
    enroll.display_name = "报名链接"

    def default_form_validation(self):
        #print("-----customer validation ",self)
        #print("----instance:",self.instance)

        consult_content =self.cleaned_data.get("content",'')
        if len(consult_content) <15:
            return self.ValidationError(
                            ('Field %(field)s 咨询内容记录不能少于15个字符'),
                            code='invalid',
                            params={'field': "content",},
                       )


    def clean_name(self):
        print("name clean validation:", self.cleaned_data["name"])
        if not self.cleaned_data["name"]:
            self.add_error('name', "cannot be null")

 

第二步是要处理表头和表内容

             <table class="table table-hover">
                  <thead>
                    <tr>
                        <th style="width: 35px"><input type="checkbox" onclick="CheckAllToggle(this)" ></th>
                        {% for column in admin_class.list_display %}
                            {% build_table_header_column column orderby_key filter_condtions admin_class%}

                        {% endfor %}
                    </tr>
                  </thead>
                  <tfoot>
                    <tr>
                        <td></td>
                        <td>总计{{ query_sets.paginator.count }}条</td></tr>
                  </tfoot>
                  <tbody>
{#                    {% get_query_sets  admin_class as query_sets %}#}
                    {% for obj in query_sets %}
                    <tr>
                        <td ><input tag="obj_checkbox" type="checkbox" value="{{ obj.id }}"></td>
                        {% build_table_row request obj admin_class %}
                    </tr>
                    {% endfor %}
                  </tbody>

              </table>

 

表头的处理:

@register.simple_tag
def  build_table_header_column(column,orderby_key,filter_condtions,admin_class):
    filters = ''
    for k,v in filter_condtions.items():
        filters += "&%s=%s" %(k,v)

    ele = '''<th><a href="?{filters}&o={orderby_key}">{column}</a>
    {sort_icon}
    </th>'''
    if orderby_key:
        if orderby_key.startswith("-"):
            sort_icon = '''<span class="glyphicon glyphicon-chevron-up"></span>'''
        else:
            sort_icon = '''<span class="glyphicon glyphicon-chevron-down"></span>'''

        if orderby_key.strip("-") == column: #排序的就是这个字段
            orderby_key =orderby_key
        else:
            orderby_key = column
            sort_icon = ''

    else:  #没有排序
        orderby_key = column
        sort_icon = ''
    try:
        column_verbose_name = admin_class.model._meta.get_field(column).verbose_name.upper()  ----这一步get_field获取不到就会报错
    except FieldDoesNotExist  as e:
        column_verbose_name = getattr(admin_class,column).display_name.upper()    -----这一步很关键
        ele = '''<th><a href="javascript:void(0);">{column}</a></th>'''.format(column=column_verbose_name)
        return mark_safe(ele)

    ele = ele.format(orderby_key=orderby_key, column=column_verbose_name,sort_icon=sort_icon,filters=filters)
    return mark_safe(ele )

 

然后是展示表数据的时候需要处理

@register.simple_tag
def build_table_row(request, obj,admin_class):
    row_ele = ""
    for index,column in enumerate(admin_class.list_display):
        try:
            field_obj = obj._meta.get_field(column)
            if field_obj.choices:#choices type,处理status这样的数字,展示为代表的汉字,
                column_data = getattr(obj,"get_%s_display" % column)()
            else:
                column_data = getattr(obj,column)

            if type(column_data).__name__ == 'datetime':
                column_data = column_data.strftime("%Y-%m-%d %H:%M:%S")

            if index == 0: #add a tag, 可以点击跳转到修改页
                column_data = "<a href='{request_path}{obj_id}/change/'>{data}</a>".format(request_path=request.path,
                                                                                            obj_id=obj.id,
                                                                                            data=column_data)
        except FieldDoesNotExist as e :
            if hasattr(admin_class,column):    -----下面的就是处理这种不存在的字段,直接调用
                column_func = getattr(admin_class,column)
                admin_class.instance = obj
                admin_class.request = request
                column_data = column_func()

        row_ele += "<td>%s</td>" % column_data

    return mark_safe(row_ele)

 

 

点击要跳转,

增加一个路由

from django.conf.urls import url
from crm import views

urlpatterns = [
    url(r'^$', views.index,name="sales_index"),
    url(r'^customer/(\d+)/enrollment/$', views.enrollment,name="enrollment"),
    url(r'^customer/registration/(\d+)/(\w+)/', views.stu_registration,name="stu_registration"),
    url(r'^contract_review/(\d+)/', views.contract_review,name="contract_review"),
    url(r'^payment/(\d+)/', views.payment,name="payment"),
    url(r'^enrollment_rejection/(\d+)/', views.enrollment_rejection,name="enrollment_rejection"),
    url(r'^customers/$', views.customer_list,name="customer_list"),
]

 

posted @ 2020-10-10 17:22  技术改变命运Andy  阅读(282)  评论(0编辑  收藏  举报