1
|
|
|
import inspect |
2
|
|
|
import sys |
3
|
|
|
from django.contrib import admin |
4
|
|
|
from django.contrib.admin import SimpleListFilter |
5
|
|
|
from django.db.models import Count |
6
|
|
|
from django.utils.html import format_html |
7
|
|
|
|
8
|
|
|
from chat import models |
9
|
|
|
from chat.models import UserJoinedInfo |
10
|
|
|
from chat.settings import STATIC_URL |
11
|
|
|
|
12
|
|
|
exclude_auto = ('UserJoinedInfo',) |
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
|
|
|
for model in model_classes: |
16
|
|
|
fields = [field.name for field in model._meta.fields if field.name not in ("password")] |
17
|
|
|
admin.site.register(model, type('SubClass', (admin.ModelAdmin,), {'fields': fields, 'list_display': fields})) |
18
|
|
|
|
19
|
|
|
|
20
|
|
|
class RegisteredFilter(SimpleListFilter): |
21
|
|
|
title = 'if registered' |
22
|
|
|
parameter_name = 'registered' |
23
|
|
|
|
24
|
|
|
def lookups(self, request, model_admin): |
25
|
|
|
return ((False, ('Registered')), (True, 'Anonymous')) |
26
|
|
|
|
27
|
|
|
def queryset(self, request, queryset): |
28
|
|
|
if self.value(): |
29
|
|
|
return queryset.filter(user__isnull=self.value() == 'True') |
30
|
|
|
else: |
31
|
|
|
return queryset |
32
|
|
|
|
33
|
|
|
|
34
|
|
|
class CountryFilter(SimpleListFilter): |
35
|
|
|
title = 'country' |
36
|
|
|
parameter_name = 'country' |
37
|
|
|
|
38
|
|
|
def lookups(self, request, model_admin): |
39
|
|
|
query_set = model_admin.model.objects.values('ip__country').annotate(count=Count('ip__country')) |
40
|
|
|
return [(c['ip__country'], '%s(%s)' % (c['ip__country'], c['count'])) for c in query_set] |
41
|
|
|
|
42
|
|
|
def queryset(self, request, queryset): |
43
|
|
|
if self.value(): |
44
|
|
|
return queryset.filter(ip__country=self.value()) |
45
|
|
|
else: |
46
|
|
|
return queryset |
47
|
|
|
|
48
|
|
|
|
49
|
|
|
@admin.register(UserJoinedInfo) |
50
|
|
|
class UserLocation(admin.ModelAdmin): |
51
|
|
|
list_display = ['username', 'country', 'region', 'city', 'provider', 'time', 'ip'] |
52
|
|
|
list_filter = (RegisteredFilter, CountryFilter, 'time') |
53
|
|
|
|
54
|
|
|
def region(self, instance): |
55
|
|
|
return instance.ip.region |
56
|
|
|
|
57
|
|
|
def city(self, instance): |
58
|
|
|
return instance.ip.city |
59
|
|
|
|
60
|
|
|
def provider(self, instance): |
61
|
|
|
return instance.ip.isp |
62
|
|
|
|
63
|
|
|
def username(self, instance): |
64
|
|
|
return instance.anon_name or instance.user |
65
|
|
|
|
66
|
|
|
def country(self, instance): |
67
|
|
|
iso2 = instance.ip.country_code if instance.ip.country_code else "None" |
68
|
|
|
return format_html("<span style='white-space:nowrap'><img src='{}/flags/{}.png' /> {}</span>", |
69
|
|
|
STATIC_URL, |
70
|
|
|
iso2.lower(), |
71
|
|
|
instance.ip.country) |
72
|
|
|
|