Skip to content

Commit

Permalink
update kingadmin
Browse files Browse the repository at this point in the history
  • Loading branch information
lijie3721 committed May 3, 2017
1 parent 37b0ce1 commit 3a8433d
Show file tree
Hide file tree
Showing 222 changed files with 24,373 additions and 201 deletions.
9 changes: 1 addition & 8 deletions CrazyEye/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
from django.contrib import admin

from web import views,api_urls
from web import cus_admin

urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
Expand All @@ -42,12 +41,6 @@
url(r'^login/$',views.login,name='login'),
url(r'^accounts/profile/$',views.personal),
url(r'^task/',include("bernard.urls")),
#url(r'^account/(\d+)/password/change/$',views.password_reset_form, name="password_change_form"),
# url(r'^configure/index/$',views.configure_index,name="table_index"),#显示所有注册的表
# url(r'^configure/(\w+)/$',views.configure_url_dispatch,name="table_list"), #显示每个表的数据
# url(r'^configure/(\w+)/change/(\d+)/$',views.table_change,name="table_change"),
# url(r'^configure/(\w+)/change/(\d+)/password/$',views.password_reset_form),
# url(r'^configure/(\w+)/add/$',views.table_add,name="table_add"),
# url(r'^configure/(\w+)/delete/(\d+)/$',views.table_del,name="table_del"),


]
Binary file modified crazyeye_db
Binary file not shown.
14 changes: 12 additions & 2 deletions kingadmin/admin_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ class BaseKingAdmin(object):
list_per_page = 20
ordering = None
filter_horizontal = []
list_editable = []
readonly_fields = []
actions = ["delete_selected_objs",]
readonly_table = False
Expand Down Expand Up @@ -45,24 +46,33 @@ def default_form_validation(self):



class AdminAlreadyRegistered(Exception):
def __init__(self,msg):
self.message = msg


class AdminSite(object):
def __init__(self, name='admin'):
self.enabled_admins = {} # model_class class -> admin_class instance
self.name = name
#self.default_actions = {'delete_selected': actions.delete_selected}
#self._global_actions = self._actions.copy()


def register(self,model_class,admin_class=None):
if model_class._meta.app_label not in self.enabled_admins:
self.enabled_admins[model_class._meta.app_label] = {} #enabled_admins['crm'] = {}
# else:
# print(self.enabled_admins)
# raise AdminAlreadyRegistered("model %s has registered already"% model_class._meta.model_name)
#admin_obj = admin_class()
if not admin_class:#no custom admin class , use BaseAdmin
admin_class = BaseKingAdmin()
admin_class.model = model_class #绑定model 对象和admin 类


self.enabled_admins[model_class._meta.app_label][model_class._meta.model_name] = admin_class
#enabled_admins['app']['tablename'] = tableadmin


site = AdminSite()

site = AdminSite()
11 changes: 11 additions & 0 deletions kingadmin/app_config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#_*_coding:utf-8_*_

from django import conf


for app in conf.settings.INSTALLED_APPS:
try:
admin_module = __import__("%s.kingadmin" % app)
#print(admin_module.kingadmin.site)
except ImportError:
pass
19 changes: 19 additions & 0 deletions kingadmin/custom_perm_logic.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#_*_coding:utf-8_*_



def only_view_own_customers(request,*args,**kwargs):
print('perm test',request,args,kwargs)

consultant_id = request.GET.get('consultant')
if consultant_id:
consultant_id = int(consultant_id)

print("consultant=1",type(consultant_id))

if consultant_id == request.user.id:
print("\033[31;1mchecking [%s]'s own customers, pass..\033[0m"% request.user)
return True
else:
print("\033[31;1muser can only view his's own customer...\033[0m")
return False
19 changes: 16 additions & 3 deletions kingadmin/forms.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
#_*_coding:utf-8_*_
from django.forms import ModelForm
from django import forms


class FormTest(forms.Form):
name = forms.CharField(max_length=32)
age = forms.IntegerField()


def __new__(cls, *args, **kwargs):
# super(CustomerForm, self).__new__(*args, **kwargs)
# self.fields['customer_note'].widget.attrs['class'] = 'form-control'
Expand Down Expand Up @@ -42,7 +49,7 @@ def default_clean(self):
'''form defautl clean method'''
# print("\033[41;1mrun form defautl clean method...\033[0m",dir(self))
# print(self.Meta.admin.readonly_fields)
# print("cleaned_dtat:",self.cleaned_data)
print("cleaned_dtat:",self.cleaned_data)
# print("validataion errors:",self.errors)
if self.Meta.admin.readonly_table is True:
raise forms.ValidationError(("This is a readonly table!"))
Expand All @@ -51,9 +58,14 @@ def default_clean(self):
if self.instance.id is not None :#means this is a change form ,should check the readonly fields
for field in self.Meta.admin.readonly_fields:
old_field_val = getattr(self.instance,field)
form_val = self.cleaned_data[field]
form_val = self.cleaned_data.get(field)
print("filed differ compare:",old_field_val,form_val)
if old_field_val != form_val:
if self.Meta.partial_update: #for list_editable feature
if field not in self.cleaned_data:
#因为list_editable成生form时只生成了指定的几个字段,所以如果readonly_field里的字段不在,list_ediatble数据里,那也不检查了
continue #

self.add_error(field,"Readonly Field: field should be '{value}' ,not '{new_value}' ".\
format(**{'value':old_field_val,'new_value':form_val}))

Expand All @@ -70,6 +82,7 @@ class Meta:
setattr(Meta,'fields',fields)
setattr(Meta,'admin',admin_class)
setattr(Meta,'form_create',form_create)
setattr(Meta,'partial_update',kwargs.get("partial_update")) #for list_editable feature, only do partial check

attrs = {'Meta':Meta}

Expand All @@ -79,5 +92,5 @@ class Meta:
setattr(model_form,'__new__',__new__)
if kwargs.get("request"): #for form validator
setattr(model_form,'_request',kwargs.get("request"))
print(model_form)
#print(model_form)
return model_form
15 changes: 9 additions & 6 deletions kingadmin/permission_list.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
#_*_coding:utf-8_*_

from kingadmin import custom_perm_logic

#权限样式 app_权限名字
perm_dic={

'crm_table_index':['table_index','GET',[]],
'crm_table_list':['table_list','GET',[]],
'crm_table_index':['table_index','GET',[],{},],
'crm_table_list':['table_list','GET',[],{}],
#'crm_table_list_action':['table_list','POST',["admin_action",]],
'crm_table_list_action':['table_list','POST',[]],
'crm_table_list_view':['table_change','GET',[]],
'crm_table_list_change':['table_change','POST',[]],
'crm_table_list_action':['table_list','POST',[],{}],
'crm_table_list_view':['table_change','GET',[],{}],
'crm_table_list_change':['table_change','POST',[],{}],
'crm_can_access_my_clients':['table_list','GET',[],
{'perm_check':33,'arg2':'test'},
custom_perm_logic.only_view_own_customers],
# 'web_invoke_admin_action':['table_list','POST',[]],
# 'web_table_change_page':['table_change','GET',[]],
# 'web_table_change':['table_change','POST',[]],
Expand Down
77 changes: 57 additions & 20 deletions kingadmin/permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,38 +14,75 @@ def perm_check(*args,**kwargs):
resolve_url_obj = resolve(request.path)
current_url_name = resolve_url_obj.url_name # 当前url的url_name
print('---perm:',request.user,request.user.is_authenticated(),current_url_name)
match_flag = False
#match_flag = False
match_key = None
if request.user.is_authenticated() is False:
return redirect(settings.LOGIN_URL)

for per_key,per_val in perm_dic.items():
per_url_name, per_method,per_args = per_val
for permission_key,permission_val in perm_dic.items():

per_url_name = permission_val[0]
per_method = permission_val[1]
perm_args = permission_val[2]
perm_kwargs = permission_val[3]
custom_perm_func = None if len(permission_val) == 4 else permission_val[4]

if per_url_name == current_url_name: #matches current request url
if per_method == request.method: #matches request method
if not per_args: #if no args defined in perm dic, then set this request to passed perm check
match_flag = True
match_key = per_key
# if not perm_args: #if no args defined in perm dic, then set this request to passed perm check
# match_flag = True
# match_key = permission_key
# else:

#逐个匹配参数,看每个参数时候都能对应的上。
args_matched = False #for args only
for item in perm_args:
request_method_func = getattr(request,per_method)
if request_method_func.get(item,None):# request字典中有此参数
args_matched = True
else:
print("arg not match......")
args_matched = False
break # 有一个参数不能匹配成功,则判定为假,退出该循环。
else:
args_matched = True
#匹配有特定值的参数
kwargs_matched = False
for k,v in perm_kwargs.items():
request_method_func = getattr(request, per_method)
arg_val = request_method_func.get(k, None) # request字典中有此参数
print("perm kwargs check:",arg_val,type(arg_val),v,type(v))
if arg_val == str(v): #匹配上了特定的参数 及对应的 参数值, 比如,需要request 对象里必须有一个叫 user_id=3的参数
kwargs_matched = True
else:
kwargs_matched = False
break # 有一个参数不能匹配成功,则判定为假,退出该循环。
else:
kwargs_matched = True

#自定义权限钩子
perm_func_matched = False
if custom_perm_func:
if custom_perm_func(request,args,kwargs):
perm_func_matched = True
else:
perm_func_matched = False #使整条权限失效

else: #没有定义权限钩子,所以默认通过
perm_func_matched = True

#逐个匹配参数,看每个参数时候都能对应的上。
for item in per_args:
request_method_fun = getattr(request,per_method)
if request_method_fun.get(item,None):# request字典中有此参数
match_flag = True
else:
match_flag = False
break # 有一个参数不能匹配成功,则判定为假,退出该循环。
match_results = [args_matched,kwargs_matched,perm_func_matched]
print("--->match_results ", match_results)
if all(match_results): #都匹配上了
match_key = permission_key
break

if match_flag == True:
match_key = per_key
break



if match_flag:
if all(match_results):
app_name, *per_name = match_key.split('_')
print("--->matched ",match_flag,match_key)
print("--->matched ",match_results,match_key)
print(app_name, *per_name)
perm_obj = '%s.%s' % (app_name,match_key)
print("perm str:",perm_obj)
Expand All @@ -67,7 +104,7 @@ def check_permission(func):
def inner(*args,**kwargs):
if not perm_check(*args,**kwargs):
request = args[0]
return render(request,'king_admin/page_403.html')
return render(request,'kingadmin/page_403.html')
return func(*args,**kwargs)
return inner

Expand Down
2 changes: 1 addition & 1 deletion kingadmin/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@

settings.STATICFILES_DIRS +=[ os.path.join(settings.BASE_DIR, 'kingadmin/statics')]

# print(settings.STATICFILES_DIRS)
print(settings.STATICFILES_DIRS)
# print(settings.TEMPLATES[0]['DIRS'] )
2 changes: 2 additions & 0 deletions kingadmin/statics/kingadmin/js/kingadmin/filter_horizontal.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
function CheckSelectedOptions() {
$("select[data-type='m2m_chosen'] option").prop("selected",true);
RemoveDisabledAttrs();
//return false;
//window.close();
}


Expand Down
16 changes: 16 additions & 0 deletions kingadmin/statics/kingadmin/js/kingadmin/king_admin.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,20 @@
*/


function PopUpWindow(src) {
//console.log("pop up src", src);
popname =window.open(src,'','width=800,height=700');
popname.window.focus();


}


function popupCallback(str,obj_id,obj_name,column_name){
//alert("This is callback:" + str);
//console.log("popup callback ",str,obj_id,obj_name,model_name)
var target_ele = $("#id_"+column_name);
target_ele.append("<option value='"+ obj_id +"' selected>"+ obj_name +"</option>" );
//console.log(target_ele.children())

}
1 change: 1 addition & 0 deletions kingadmin/tables.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ def __init__(self, request, model_class, admin_class, query_sets, order_res):
self.model_name = self.model_class._meta.model_name
# self.admin_class = admin_class
self.actions = admin_class.actions
self.list_editable = admin_class.list_editable
self.query_sets = query_sets
#self.choice_fields = admin_class.choice_fields
#self.fk_fields = admin_class.fk_fields
Expand Down
3 changes: 3 additions & 0 deletions kingadmin/templates/kingadmin/app_index.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@

</ol>
{% endblock %}



{% block page-content %}

{% for app_name,admin_class_dic in enabled_admins.items %}
Expand Down
4 changes: 2 additions & 2 deletions kingadmin/templates/kingadmin/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@
<!--STYLESHEET-->
<!--=================================================-->

<!--Open Sans Font [ OPTIONAL ] -->
<link href="http://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700&amp;subset=latin" rel="stylesheet">
<!--Open Sans Font [ OPTIONAL ]
<link href="http://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700&amp;subset=latin" rel="stylesheet" -->


<!--Bootstrap Stylesheet [ REQUIRED ]-->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<div>
<div style="width: 380px;float: left">
{# {% get_attr field %}#}
<p>可选 </p>
<p>可选 {% add_new_obj_btn form_obj field %} </p>
<input autocomplete="off" id='_search_{{ field.name }}' oninput="FuzzySearch('{{ field.name }}')" type="text" class="form-control" placeholder="Search..">


Expand Down
Loading

0 comments on commit 3a8433d

Please sign in to comment.