Completed
Push — master ( 04c3f6...3ca933 )
by Andrew
25s
created

country()   A

Complexity

Conditions 2

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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