Completed
Push — master ( 370628...15eca4 )
by Andrew
26s
created

time()   A

Complexity

Conditions 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 1
c 1
b 1
f 0
dl 0
loc 3
rs 10
1
import inspect
2
import json
3
import sys
4
from datetime import datetime
5
6
from django.conf import settings
7
from django.contrib import admin
8
from django.db.models import ForeignKey
9
from django.utils.html import format_html
10
11
from chat import models
12
13
exclude_auto = ('User')
14
model_classes = (class_name[1] for class_name in inspect.getmembers(sys.modules[models.__name__], inspect.isclass)
15
					if class_name[1].__module__ == models.__name__ and class_name[0] not in exclude_auto)
16
17
def gen_fun(field):
18
	def col_name(o):
19
		attr = getattr(o, field)
20
		v = json.dumps(attr)
21
		if len(v) > 50:
22
			v = v[:50]
23
		return v
24
	return col_name
25
26
27
def country(instance):
28
	iso2 = instance.country_code if instance.country_code else "None"
29
	return format_html("<span style='white-space:nowrap'><img src='{}/flags/{}.png' /> {}</span>",
30
							 settings.STATIC_URL,
31
							 iso2.lower(),
32
							 instance.country)
33
34
def time(instance):
35
	d = datetime.fromtimestamp(instance.time / 1000 ).strftime('%Y-%m-%d %H:%M:%S')
36
	return format_html("<span style='white-space:nowrap'>{}</span>", d)
37
38
39
extra_fields = {
40
	'ip address': (country,),
41
	'message': (time,),
42
}
43
44
exclude_fields = {
45
	'ip address': ('country',),
46
	'message': ('time',),
47
}
48
49
list_filter = {
50
	'message': ('room', 'deleted', 'sender'),
51
	'room': ('disabled',),
52
	'ip address': ('country', 'region', 'city'),
53
	'room users': ('notifications', 'user', 'room'),
54
	'subscription': ('user', 'inactive', 'is_mobile', 'created', 'updated'),
55
	'subscription messages': ('subscription', 'received', 'message'),
56
	'user joined info': ('user', 'time'),
57
	'issue details': ('sender', 'time'),
58
	'user': ('sex',),
59
	'user profile': ('last_login', 'sex'),
60
	'verification': ('verified', 'time'),
61
}
62
63
for model in model_classes:
64
	fields = []
65
	list_display = []
66
	vname = model._meta.verbose_name
67
	class_struct = {'fields': fields, 'list_display': list_display}
68
	if list_filter.get(vname) is not None:
69
		class_struct['list_filter'] = list_filter.get(vname)
70
	for field in model._meta.fields:
71
		if field.name in exclude_fields.get(vname, []):
72
			continue
73
		if field.name != 'id' and field.name != 'user_ptr':
74
			fields.append(field.name)
75
		if isinstance(field, ForeignKey):
76
			def gen_link(field):
77
				def link(obj):
78
					print(field)
79
					another = getattr(obj, field.name)
80
					if another is None:
81
						return "Null"
82
					else:
83
						another_name = another._meta.verbose_name
84
						another_link = another_name if another_name != 'user' else 'userprofile'
85
						link = '/admin/chat/{}/{}/change'.format(another_link, another.id)
86
						return u'<a href="%s">%s</a>' % (link, str(another))
87
				link.allow_tags = True
88
				link.__name__ = str(field.name)
89
				return link
90
			list_display.append(gen_link(field))
91
		else:
92
			list_display.append(field.name)
93
	if extra_fields.get(vname) is not None:
94
		list_display.extend(extra_fields.get(vname))
95
	admin.site.register(model, type(
96
		'SubClass',
97
		(admin.ModelAdmin,),
98
		class_struct
99
	))
100
101
102
# class CountryFilter(SimpleListFilter):
103
# 	title = 'country'
104
# 	parameter_name = 'country'
105
#
106
# 	def lookups(self, request, model_admin):
107
# 		query_set = model_admin.model.objects.values('ip__country').annotate(count=Count('ip__country'))
108
# 		return [(c['ip__country'], '%s(%s)' % (c['ip__country'], c['count'])) for c in query_set]
109
#
110
# 	def queryset(self, request, queryset):
111
# 		if self.value():
112
# 			return queryset.filter(ip__country=self.value())
113
# 		else:
114
# 			return queryset
115
#
116
#
117
# @admin.register(UserJoinedInfo)
118
# class UserLocation(admin.ModelAdmin):
119
# 	list_display = ["time", "link_to_B"]
120
#
121
# 	def link_to_B(self, obj):
122
# 		link = urlresolvers.reverse("admin:chat_user_change", args=[obj.Object.id])  # model name has to be lowercase
123
# 		return u'<a href="%s">%s</a>' % (link, obj.B.name)
124
#
125
# 	link_to_B.allow_tags = True
126