admin.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import random
  2. from django import forms
  3. from django.urls import reverse
  4. from django.utils.html import format_html, format_html_join
  5. from django.contrib import admin
  6. from .models import Group, Person
  7. from .forms import PersonAdminForm
  8. def random_color():
  9. r = lambda: random.randint(0,255)
  10. return '#{:02x}{:02x}{:02x}'.format(r(), r(), r())
  11. @admin.register(Person)
  12. class PersonAdmin(admin.ModelAdmin):
  13. list_select_related = ('parent', 'group')
  14. list_display = ['name', 'get_partners', 'get_parent', 'birth_date', 'death_date', 'comment', 'color', 'group']
  15. list_editable = ['color']
  16. list_filter = ('group', 'birth_date')
  17. search_fields = ['name', 'birth_date', 'birth_town', 'death_date', 'death_town', 'comment']
  18. ordering = ('group','name')
  19. filter_horizontal = ('partners',)
  20. fields = ('name', 'parent', 'partners', 'children', 'birth_date', 'birth_town', 'death_date', 'death_town', 'comment', 'image', 'image_tag', 'color', 'group')
  21. readonly_fields = ('image_tag', 'children')
  22. def get_queryset(self, request):
  23. qs = super().get_queryset(request)
  24. return qs.prefetch_related('partners')
  25. def get_partners(self, obj):
  26. return format_html_join(', ', '<a href="{}">{}</a>', [(reverse("admin:stammbaum_person_change", args=[p.id]), p) for p in obj.partners.all()])
  27. get_partners.short_description = "Partner"
  28. def get_parent(self, obj):
  29. if obj.parent:
  30. return format_html('<a href="{}">{}</a>', reverse("admin:stammbaum_person_change", args=[obj.parent.id]), obj.parent)
  31. get_parent.short_description = "Eltern"
  32. def children(self, obj):
  33. return format_html_join(', ', '<a href="{}">{}</a>', [(reverse("admin:stammbaum_person_change", args=[p.id]), p) for p in Person.objects.filter(parent=obj)])
  34. def save_related(self, request, form, formsets, change):
  35. super(PersonAdmin, self).save_related(request, form, formsets, change)
  36. partners = form.instance.partners.all()
  37. if not form.instance.color and len(partners) > 0:
  38. color = random_color()
  39. for partner in partners:
  40. if partner.color:
  41. color = partner.color
  42. break
  43. form.instance.color = color
  44. form.instance.save()
  45. for partner in partners:
  46. print(partner)
  47. partner.color = form.instance.color
  48. partner.save()
  49. form = PersonAdminForm
  50. @admin.register(Group)
  51. class GroupAdmin(admin.ModelAdmin):
  52. list_display = ['name', 'color']
  53. list_editable = ['name', 'color']
  54. list_display_links = None
  55. ordering = ('name',)