django_coreprotect/admin.py

73 lines
2.7 KiB
Python

from django.contrib import admin
from django.contrib.admin import widgets as admin_widgets
from django import forms
import ast
from django_coreprotect.utils import time_to_form, form_to_time
from django_coreprotect.models import CoArtMap, CoBlock, CoBlockdataMap, CoChat, CoCommand, CoContainer, CoDatabaseLock, \
CoEntity, CoEntityMap, CoMaterialMap, CoSession, CoSign, CoSkull, CoUser, CoUsernameLog, CoVersion, CoWorld, Preset
class PresetAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(PresetAdminForm, self).__init__(*args, **kwargs)
worlds = tuple([(world.id, world.world) for world in CoWorld.objects.all()])
self.fields['worlds'].widget = forms.SelectMultiple(choices=worlds)
self.fields['date_from'].widget = admin_widgets.AdminSplitDateTime()
self.fields['date_to'].widget = admin_widgets.AdminSplitDateTime()
if self.instance:
if "worlds" in self.initial and self.initial["worlds"]:
self.initial["worlds"] = tuple(self.initial["worlds"])
if "date_from" in self.initial and self.initial["date_from"]:
self.initial["date_from"] = time_to_form(self.initial["date_from"])
if "date_to" in self.initial and self.initial["date_to"]:
self.initial["date_to"] = time_to_form(self.initial["date_to"])
def clean(self):
cleaned = super(PresetAdminForm, self).clean()
worlds = cleaned.get("worlds", "")
if worlds:
worlds = ast.literal_eval(worlds)
cleaned.update({"worlds": ",".join(worlds)})
date_from = cleaned.get("date_from", "")
if date_from:
cleaned.update({"date_from": form_to_time(date_from)})
date_to = cleaned.get("date_to", "")
if date_to:
cleaned.update({"date_to": form_to_time(date_to)})
return cleaned
class Meta:
model = Preset
fields = "__all__"
class PresetAdmin(admin.ModelAdmin):
form = PresetAdminForm
try:
pass
# admin.site.register(CoArtMap)
# admin.site.register(CoBlock)
# admin.site.register(CoBlockdataMap)
# admin.site.register(CoChat)
# admin.site.register(CoCommand)
# admin.site.register(CoContainer)
# admin.site.register(CoDatabaseLock)
# admin.site.register(CoEntity)
# admin.site.register(CoEntityMap)
# admin.site.register(CoMaterialMap)
# admin.site.register(CoSession)
# admin.site.register(CoSign)
# admin.site.register(CoSkull)
# admin.site.register(CoUser)
# admin.site.register(CoUsernameLog)
# admin.site.register(CoVersion)
# admin.site.register(CoWorld)
admin.site.register(Preset, PresetAdmin)
except admin.sites.AlreadyRegistered:
pass