Пример #1
0
def DataDetailResponse(request,
                       dataModel,
                       form,
                       key=None,
                       instance=None,
                       **kargs):
    '''
    编辑页直接视图
    '''
    from urls import get_model_data_url, dbapp_url
    from django.db import models
    import base
    from django.contrib.contenttypes.models import ContentType
    if not kargs: kargs = {}
    tmp_file = request.GET.get('_t', "%s.html" % form.__class__.__name__)
    kargs["dbapp_url"] = dbapp_url
    request.dbapp_url = dbapp_url
    kargs["form"] = form
    kargs["title"] = (u"%s" % dataModel._meta.verbose_name).capitalize()
    kargs["dataOpt"] = dataModel._meta
    kargs['model_name'] = dataModel.__name__
    kargs['app'] = dataModel._meta.app_label
    if issubclass(dataModel, models.Model):
        kargs["app_menu"] = hasattr(
            dataModel.Admin, "app_menu"
        ) and dataModel.Admin.app_menu or dataModel._meta.app_label
    kargs["add"] = key == None
    kargs["instance"] = instance
    if key and issubclass(dataModel,
                          base.models.CachingModel) and dataModel.Admin.log:
        try:
            ct = ContentType.objects.get_for_model(dataModel)
            kargs['log_url'] = get_model_data_url(
                base.models.LogEntry) + ("?content_type__id=%s&object_id=%s" %
                                         (ct.pk, key))
            kargs['log_search'] = ("content_type__id=%s&object_id=%s" %
                                   (ct.pk, key))
        except:
            print_exc()
    if hasattr(dataModel.Admin, "form_tabs"):
        kargs["tabs"] = dataModel.Admin.form_tabs
    if hasattr(dataModel.Admin, "form_before_response"):
        dataModel.Admin.form_before_response(request, kargs, key)
    kargs["position"] = hasattr(
        dataModel.Admin, "position") and dataModel.Admin.position or None
    pre_detail_response.send(sender=kargs, dataModel=dataModel, key=key)
    template_list = [
        tmp_file, dataModel.__name__ + '_edit.html', 'data_edit.html'
    ]
    return render_to_response(
        template_list,
        RequestContext(request, kargs),
    )
Пример #2
0
def DataDetailResponse(request, dataModel, form, key=None, instance=None, **kargs):
    '''
    编辑页直接视图
    '''
    from urls import get_model_data_url, dbapp_url
    from django.db import models
    import base
    from django.contrib.contenttypes.models import ContentType
    if not kargs: kargs={}
    tmp_file=request.GET.get('_t',"%s.html"%form.__class__.__name__)
    kargs["dbapp_url"]=dbapp_url
    request.dbapp_url=dbapp_url
    kargs["form"]=form
    kargs["title"]=(u"%s"%dataModel._meta.verbose_name).capitalize()
    kargs["dataOpt"]=dataModel._meta
    kargs['model_name']=dataModel.__name__
    kargs['app']=dataModel._meta.app_label
    if issubclass(dataModel,models.Model):
        kargs["app_menu"]=hasattr(dataModel.Admin,"app_menu") and dataModel.Admin.app_menu or  dataModel._meta.app_label
    kargs["add"]=key==None
    kargs["instance"]=instance
    if key and issubclass(dataModel, base.models.CachingModel) and dataModel.Admin.log:
            try:
                    ct=ContentType.objects.get_for_model(dataModel)
                    kargs['log_url']=get_model_data_url(base.models.LogEntry)+("?content_type__id=%s&object_id=%s"%(ct.pk,key))
                    kargs['log_search']=("content_type__id=%s&object_id=%s"%(ct.pk,key))
            except:
                    print_exc()
    if hasattr(dataModel.Admin, "form_tabs"):
            kargs["tabs"]=dataModel.Admin.form_tabs
    if hasattr(dataModel.Admin, "form_before_response"):
        dataModel.Admin.form_before_response(request, kargs, key)
    kargs["position"] = hasattr(dataModel.Admin, "position") and dataModel.Admin.position or None
    pre_detail_response.send(sender=kargs, dataModel=dataModel, key=key)
    template_list = [tmp_file, dataModel.__name__+'_edit.html','data_edit.html']
    return render_to_response(template_list, RequestContext(request,kargs),)        
Пример #3
0
def model_data_list(request,
                    dataModel,
                    qs=None,
                    model_url=None,
                    ignore_keys=None):
    from urls import dbapp_url, surl
    from dbapp.datautils import exist_perm
    from data_edit import form_for_model
    from dbapp.viewmodels import get_all_view
    from mysite.utils import get_option
    #    from mysite import authorize_fun

    #    #软件狗控制/*******start*******/
    #    if not authorize_fun.can_get_datalist(request):
    #        if request.is_ajax():
    #            return HttpResponse("session_fail_or_no_permission")
    #        else:
    #            return render_to_response('no_permission_info.html',RequestContext(request,{'dbapp_url': dbapp_url}))
    #    #/********end**********/
    lng = get_language()

    action = request.REQUEST.get(ACTION_VAR, "")
    if len(action) > 0:
        checkAction = action
        if not hasPerm(request.user, dataModel, checkAction):
            return getJSResponse(u"{ errorCode:-2,errorInfo:\"%s\"}" %
                                 _(u"你没有该权限!"))  #NoPermissionResponse()
        resp = doAction(action, request, dataModel)
        if resp: return resp

    if not hasPerm(request.user, dataModel, "browse"):
        #默认把浏览权限赋予配置的模块
        #print"......no pemission",dataModel.__name__
        if hasattr(
                dataModel.Admin,
                "default_give_perms") and dataModel.Admin.default_give_perms:
            #print ".........have default perms=",dataModel.Admin.default_give_perms
            flag = False
            for perm in dataModel.Admin.default_give_perms:
                if request.user.has_perm(perm):
                    flag = True
                    break
            #print "........flag=",flag
            if not flag:
                if request.is_ajax():
                    return HttpResponse(_(u'会话已过期或没有权限'))
                else:
                    return render_to_response(
                        'no_permission_info.html',
                        RequestContext(request, {'dbapp_url': dbapp_url}))
        else:
            if request.is_ajax():
                return HttpResponse(_(u'会话已过期或没有权限'))
            else:
                return render_to_response(
                    'no_permission_info.html',
                    RequestContext(request, {'dbapp_url': dbapp_url}))

    master = get_model_master(dataModel)
    request.model = dataModel
    request.dbapp_url = dbapp_url  #已经加到中间件中了
    #可以缓存的参数
    cache_key = "%s_%s_cc" % (lng, dataModel.__name__)
    cache_cc = cache.get(cache_key)
    if not cache_cc:
        searchform = ""
        if hasattr(dataModel.Admin,
                   "query_fields") and dataModel.Admin.query_fields:
            searchform = seachform_for_model(request,
                                             dataModel,
                                             fields=list(
                                                 dataModel.Admin.query_fields))
        cache_cc = {
            'title': (u"%s" % dataModel._meta.verbose_name).capitalize(),
            'app_label':
            dataModel._meta.app_label,
            'model_name':
            dataModel.__name__,
            'dbapp_url':
            dbapp_url,
            'model_url':
            model_url or request.dbapp_url + dataModel._meta.app_label + "/" +
            dataModel.__name__ + "/",
            'searchform':
            searchform,
            'import_perm':
            dataModel._meta.app_label + ".dataimport_" +
            dataModel.__name__.lower(),
            'export_perm':
            dataModel._meta.app_label + ".browse_" +
            dataModel.__name__.lower(),
            'menu_focus':
            hasattr(dataModel.Admin, "menu_focus")
            and dataModel.Admin.menu_focus
            or dataModel.__name__,  #用于跟模型相关的菜单获取焦点
            'position':
            hasattr(dataModel.Admin, "position")
            and unicode(dataModel.Admin.position) or None,
            'pin_support_letters':
            (settings.PIN_SUPPORT_LETTERS and get_option("ONLY_ATT")) and 1
            or 0,
        }

        cache.set(cache_key, cache_cc, 60 * 60 * 24 * 7)
    #不能缓存的参数
    qs, cl = QueryData(request, dataModel, master, qs, ignore_keys)
    try:
        offset = int(request.REQUEST.get(PAGE_VAR, 1))
    except:
        offset = 1
    limit = int(request.REQUEST.get(PAGE_LIMIT_VAR, settings.PAGE_LIMIT))

    try:
        mnp = int(request.REQUEST.get(MAX_NO_PAGE, 50))
        if qs.count() <= mnp:
            limit = mnp
    except:
        limit = 50

    cc = {
        'from': (offset - 1) * limit + 1,
        'page': offset,
        'limit': limit,
        'cl': cl,
    }
    cc.update(cache_cc)
    isProcessed = False
    for ret in on_list_paginator.send(sender=cc,
                                      request=request,
                                      dataModel=dataModel,
                                      querySet=qs):
        if ret[1]:
            isProcessed = True
            break
    if not isProcessed:
        paginator = Paginator(qs, limit)
        item_count = paginator.count
        if offset > paginator.num_pages:
            offset = paginator.num_pages
            cc['page'] = offset
        if offset < 1: offset = 1
        pgList = paginator.page(offset)
        cc['latest_item_list'] = pgList.object_list
        cc['page_count'] = paginator.num_pages
        cc['item_count'] = item_count

        list_exception_fields = request.REQUEST.getlist("exception_fields")
        list_addition_fields = request.REQUEST.getlist("addition_fields")

        if master:
            master2str = master.name
        else:
            master2str = ""

        cache_key = lng + "_" + dataModel.__name__ + "_".join(
            list_exception_fields + list_addition_fields) + master2str
        t = cache.get(cache_key)
        if not t:
            t = getDefaultJsonDataTemplate(dataModel, list_exception_fields,
                                           list_addition_fields, master)
            cache.set(cache_key, t, 60 * 60 * 24 * 7)

        var_options = u"""record_count:{{ item_count }},
                                        item_from:{{ from }},
                                        current_page:{{ page }},
                                        page_limit:{{ limit }},
                                        page_count:{{ page_count }},
                                        order_by:"{{ order_by }}",
                                        'options':%s,
                                        'actions':%s
                        """ % getUsrCreateFrameOptions(dataModel, request)

        t = "{ \n " + t + var_options + " \n }"
        t_r = Template(t).render(RequestContext(request, cc))
    if request.method == 'POST':
        return getJSResponse(smart_str(t_r))

    from urls import get_model_data_url
    from base import get_all_app_and_models
    import base
    if issubclass(dataModel, base.models.CachingModel) and dataModel.Admin.log:
        try:
            ct = ContentType.objects.get_for_model(dataModel)
            cc['log_url'] = get_model_data_url(
                base.models.LogEntry) + ("?content_type__id=%s" % ct.pk)
            cc['log_search'] = "content_type__id=%s" % ct.pk
        except:
            print_exc()
    apps = get_all_app_and_models()
    cc["apps"] = apps
    admin = hasattr(dataModel, "Admin") and dataModel.Admin or None
    current_app = hasattr(
        admin, "app_menu") and admin.app_menu or dataModel._meta.app_label
    cc["current_app"] = current_app
    try:
        cc["myapp"] = [a for a in apps if a[0] == current_app][0][1]
    except:
        pass

    cache_key = "%s_%s_template" % (lng, dataModel.__name__)
    tmp_file = cache.get(cache_key)
    if not tmp_file:
        tmp_file = loader.select_template([
            dataModel._meta.app_label + "." + dataModel.__name__ + ".html",
            dataModel.__name__ + "_list.html",
            "data_list_" + dataModel._meta.app_label + ".html",
            "data_list.html"
        ])
        #cache.set(cache_key,tmp_file,60*60*24*7)
    cc["query"] = "&".join(
        [k + "=" + v[0] for k, v in dict(request.GET).items()])
    cc['datalist'] = smart_str(t_r)
    return HttpResponse(tmp_file.render(RequestContext(request, cc)))
Пример #4
0
def model_data_list(request, dataModel, qs=None, model_url=None):
    '''
    通用列表视图
    '''
#    if qs:
#        print 'qs-----------------------------------:',qs
    from urls import dbapp_url, surl
    from dbapp.data_utils import exist_perm
    from data_edit import form_for_model
    from dbapp.viewmodels import get_all_view         
    lng=get_language()  # 获取语言
    
    action=request.REQUEST.get(ACTION_VAR, "")  # 获取动作类型
    if len(action)>0:
            checkAction=action
            if not hasPerm(request.user, dataModel, checkAction):   # 动作权限的判断
                    return getJSResponse(u"{ errorCode:-2,errorInfo:\"%s\"}"%_(u"你没有该权限!")) # 返回 js 内容
            resp=doAction(action, request, dataModel)
            if resp: return resp
    ##################### 判断是否有 default_give_perms 权限  ############################
    if not hasPerm(request.user, dataModel, "browse"): # 没有 browse 权限 模型是否有default_give_perms项            
            if  hasattr(dataModel.Admin,"default_give_perms") and  dataModel.Admin.default_give_perms:
                flag=False
                for perm in  dataModel.Admin.default_give_perms:
                    if request.user.has_perm(perm):
                        flag=True
                        break
                if not flag:
                    if request.is_ajax():
                        return HttpResponse("session_fail_or_no_permission")
                    else:
                        return render_to_response('no_permission_info.html',RequestContext(request,{'dbapp_url': dbapp_url}))
            else:
                if request.is_ajax():
                    return HttpResponse("session_fail_or_no_permission")
                else:
                    return render_to_response('no_permission_info.html',RequestContext(request,{'dbapp_url': dbapp_url}))
    
    master=get_model_master(dataModel)
    request.model=dataModel
    request.dbapp_url=dbapp_url #已经加到中间件中了 /data/
    
    # 取缓存
    cache_key="%s_%s_cc"%(lng,dataModel.__name__)   # zh-cn_model_1_cc
    cache_cc=cache.get(cache_key)
    if not cache_cc:
        searchform=""
        if hasattr(dataModel.Admin,"query_fields") and dataModel.Admin.query_fields:        
                searchform=seachform_for_model(request,dataModel,fields=list(dataModel.Admin.query_fields)) # 查询表单html内容  
        cache_cc={
            'title': (u"%s"%dataModel._meta.verbose_name).capitalize(),
            'app_label':dataModel._meta.app_label,
            'model_name':dataModel.__name__,
            'dbapp_url': dbapp_url,
            'model_url': model_url or request.dbapp_url+dataModel._meta.app_label+"/"+dataModel.__name__+"/",
            'searchform':searchform,
            'import_perm':dataModel._meta.app_label+".dataimport_"+dataModel.__name__.lower(),  # 导入标识名
            'export_perm':dataModel._meta.app_label+".dataexport_"+dataModel.__name__.lower(),  # 导出标识名
            'menu_focus':hasattr(dataModel.Admin, "menu_focus") and dataModel.Admin.menu_focus or dataModel.__name__, #用于跟模型相关的菜单获取焦点
            'position':hasattr(dataModel.Admin, "position") and dataModel.Admin.position or None,
        }
        cache.set(cache_key,cache_cc,60*60*24*7)    # 参数字典 加入缓存

    ####################### 得到分页和排序参数字典 这些参数不缓存 #####################
    qs, cl=QueryData(request, dataModel, master, qs)    # 模型数据查询
    try:
            offset = int(request.REQUEST.get(PAGE_VAR, 1))
    except:
            offset=1
    limit= int(request.REQUEST.get(PAGE_LIMIT_VAR, settings.PAGE_LIMIT))
    
    try:
        mnp=int(request.REQUEST.get(MAX_NO_PAGE, 50))
        if qs.count()<=mnp:
            limit=mnp
    except:
        limit=50

    cc={
            'from': (offset-1)*limit+1,
            'page': offset,
            'limit': limit,
            'cl': cl,
            }
    cc.update(cache_cc) # 合并前面的参数字典
    
    isProcessed=False
    for ret in on_list_paginator.send(sender=cc, request=request, dataModel=dataModel, querySet=qs):
            if ret[1]:
                    isProcessed=True
                    break
    if not isProcessed:
            paginator = Paginator(qs, limit)    # django 的分页对象
            item_count = paginator.count
            if offset>paginator.num_pages: 
                offset=paginator.num_pages
                cc['page']=offset
            if offset<1: offset=1
            pgList = paginator.page(offset)
            cc['latest_item_list']=pgList.object_list   # 分页结果数据
            cc['page_count']=paginator.num_pages
            cc['item_count']=item_count
            
            list_exception_fields=request.REQUEST.getlist("exception_fields")
            list_addition_fields=request.REQUEST.getlist("addition_fields")
            
            if master:
                master2str=master.name
            else:
                master2str=""                
            cache_key=lng+"_"+dataModel.__name__+"_".join(list_exception_fields+list_addition_fields)+master2str
            t=cache.get(cache_key)  # 缓存 DefaultJsonDataTemplate
            if not t:
                t=getDefaultJsonDataTemplate(dataModel,list_exception_fields,list_addition_fields,master)
                cache.set(cache_key,t,60*60*24*7)
            
            var_options=u"""record_count:{{ item_count }},
                                        item_from:{{ from }},
                                        current_page:{{ page }},
                                        page_limit:{{ limit }},
                                        page_count:{{ page_count }},
                                        order_by:"{{ order_by }}",
                                        'options':%s,
                                        'actions':%s
                        """%getUsrCreateFrameOptions(dataModel,request) # 得到Options集合信息
                        
            t="{ \n "+t+var_options+" \n }"
            t_r=Template(t).render(RequestContext(request, cc)) #---------------------------------一部分内容
    if request.method=='POST':  # 如果是ajax请求------------------------------------------------------------------------------------------如“日志记录”
            return getJSResponse(smart_str(t_r))

    from urls import get_model_data_url
    from base import get_all_app_and_models
    import base
    if issubclass(dataModel, base.models.CachingModel) and dataModel.Admin.log:
            try:
                    ct=ContentType.objects.get_for_model(dataModel)
                    cc['log_url']=get_model_data_url(base.models.LogEntry)+("?content_type__id=%s"%ct.pk)
                    cc['log_search']="content_type__id=%s"%ct.pk
            except: 
                    print_exc()
    apps=get_all_app_and_models()
    cc["apps"]=apps
    admin=hasattr(dataModel, "Admin") and dataModel.Admin or None
    current_app=hasattr(admin, "app_menu") and admin.app_menu or dataModel._meta.app_label
    cc["current_app"]=current_app
    try:
        cc["myapp"]=[a for a in apps if a[0]==current_app][0][1]    # 所在app的所有信息
    except:
        pass
    
    cache_key="%s_%s_template"%(lng,dataModel.__name__)
    tmp_file=cache.get(cache_key)
    if not tmp_file:
        tmp_file=loader.select_template([
                dataModel._meta.app_label+"."+dataModel.__name__+".html", 
                dataModel.__name__+"_list.html", 
                "data_list_"+dataModel._meta.app_label+".html",
                "data_list.html"])
        #cache.set(cache_key,tmp_file,60*60*24*7)
    
    cc["query"]="&".join([k+"="+v[0] for k,v in dict(request.GET).items()]) # 查询参数
    cc['datalist']=smart_str(t_r)   # 主要数据
    return HttpResponse(tmp_file.render(RequestContext(request, cc)))