import random
from django import forms
from django.urls import reverse
from django.utils.html import format_html, format_html_join
from django.contrib import admin
from .models import Group, Person
from .forms import PersonAdminForm
def random_color():
r = lambda: random.randint(0,255)
return '#{:02x}{:02x}{:02x}'.format(r(), r(), r())
@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):
list_select_related = ('parent', 'group')
list_display = ['name', 'get_partners', 'get_parent', 'birth_date', 'death_date', 'comment', 'color', 'group']
list_editable = ['color']
list_filter = ('group', 'birth_date')
search_fields = ['name', 'birth_date', 'birth_town', 'death_date', 'death_town', 'comment']
ordering = ('group','name')
filter_horizontal = ('partners',)
fields = ('name', 'parent', 'partners', 'children', 'birth_date', 'birth_town', 'death_date', 'death_town', 'comment', 'image', 'image_tag', 'color', 'group')
readonly_fields = ('image_tag', 'children')
def get_queryset(self, request):
qs = super().get_queryset(request)
return qs.prefetch_related('partners')
def get_partners(self, obj):
return format_html_join(', ', '{}', [(reverse("admin:stammbaum_person_change", args=[p.id]), p) for p in obj.partners.all()])
get_partners.short_description = "Partner"
def get_parent(self, obj):
if obj.parent:
return format_html('{}', reverse("admin:stammbaum_person_change", args=[obj.parent.id]), obj.parent)
get_parent.short_description = "Eltern"
def children(self, obj):
return format_html_join(', ', '{}', [(reverse("admin:stammbaum_person_change", args=[p.id]), p) for p in Person.objects.filter(parent=obj)])
def save_related(self, request, form, formsets, change):
super(PersonAdmin, self).save_related(request, form, formsets, change)
partners = form.instance.partners.all()
if not form.instance.color and len(partners) > 0:
color = random_color()
for partner in partners:
if partner.color:
color = partner.color
break
form.instance.color = color
form.instance.save()
for partner in partners:
print(partner)
partner.color = form.instance.color
partner.save()
form = PersonAdminForm
@admin.register(Group)
class GroupAdmin(admin.ModelAdmin):
list_display = ['name', 'color']
list_editable = ['name', 'color']
list_display_links = None
ordering = ('name',)